Здравствуйте!
— Не хотите ли войти
1
ответ

[UIView beginAnimation] + NSTimer

#import "ExerciseWork.h"
#import <stdlib.h>
//Количество упражнений, выбираемое в список
#define exercisesListSize 10
//Длительность каждого упражнения
#define exerciseDuration 10

@implementation ExerciseWork

//Все упражнения, доступные в программе.
NSMutableArray *exercises;
//Список из нескольких упражнений, составленный на основе полного.
NSMutableArray *currentExerciseList;
//Массив точек для текущего упражнения
NSMutableArray *pointsFromExercise;
//Полное количество упражнений
int exercisesCount;
//Номер текущего упражнения из списка
int currentExercise;
//Время, прошедшее с момента старта таймера
int tickCount;
//Текущая точка, к которой стремится шарик
int currentPoint;

//Считать все упражнения из файла в список. Размер этого списка - любой ненулевой.
- (void)readExercisesFromPlist:(NSString *)name {
	NSString *path = [[NSBundle mainBundle] bundlePath];
	NSString *finalPath = [path stringByAppendingPathComponent:name];
	exercises = [[NSMutableArray alloc] initWithContentsOfFile:finalPath];
	exercisesCount = [exercises count];
}

//Выбрать некоторые упражнения и составить из них новый список. Размер этого списка постоянный и "зашит" в программе.
- (void)createCurrentExercisesList {
	[timer invalidate];
	timerIsRunning = NO;
	while ([currentExerciseList count] > 0) {
		[currentExerciseList removeObjectAtIndex:0];
	}
	[currentExerciseList release];
	currentExerciseList = [[NSMutableArray alloc] init];
	for (int i = 0; i < exercisesListSize; i++) {
		int n = arc4random() % exercisesCount;
		[currentExerciseList addObject:[[exercises objectAtIndex:n] copy]];
	}
}

//Перейти к следующему упражнению
- (void)nextExercise {
	currentExercise++;
	pointsFromExercise = [[NSMutableArray alloc] initWithArray:[currentExerciseList objectAtIndex:currentExercise]];
}

//Следующая точка текущего упражнения
- (void)nextPoint {
	currentPoint++;
	if (currentPoint == [[pointsFromExercise objectAtIndex:0] count]) {
		currentPoint = 0;
	}
}

//Стартовать или остановить общий таймер
- (void)startOrStopTimer {
	if (timerIsRunning) {
		[timer invalidate];
	} else {
		timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDownOneSecond) userInfo:nil repeats:YES];
	}
	
	timerIsRunning = !timerIsRunning;
}

//Процедура для таймера
- (void)countDownOneSecond {
	dx = [[[pointsFromExercise objectAtIndex:0] objectAtIndex:currentPoint] intValue];
	dy = [[[pointsFromExercise objectAtIndex:1] objectAtIndex:currentPoint] intValue];
	[self nextPoint];
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:1];
//	[UIView setAnimationBeginsFromCurrentState:YES];
	ball.transform = CGAffineTransformMakeTranslation(dx, dy);
	[UIView commitAnimations];
	tickCount++;
//	[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
//	timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDownOneSecond) userInfo:nil repeats:NO];
}

//Начать упражнения
- (void)startExercise:(UIImageView *)myBall {	 
	[self createCurrentExercisesList];
	ball = myBall;
	tickCount = 0;
	currentExercise = -1;	//Поскольку номера упражнений начинаются с -1
	currentPoint = 0;
	[self nextExercise];
	[self startOrStopTimer];
}


@end

При каждом вызове startExercise анимация как будто добавляется к уже существующей и перерисовка вызывается уже чаще чем раз в секунду. В итоге на экране анимация рывками.

11 августа 2010

Ответы

  1. Спискам можно послать сообщение removeAllObjects, кажется, вместо удаления по-одному.
  2. При удалении списка, удаляются все элементы, то есть можно просто сделать release списку и все будет хорошо.
  3. А проблема, возможно, кроется тут (описание сообщения invalidate в NSTimer):
Special Considerations

You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly.»
11 августа 2010
Зарегистрируйтесь или войдите, чтобы добавить свой комментарий или ответ на вопрос.
© 2009-2012, ООО «Инру»
Вход
Имя пользователя:
Пароль:
Или…
Twi
Отмена
Войти
Восстановить забытый пароль…