优化在Obj C中调用自身的函数

时间:2018-06-22 18:21:36

标签: objective-c function

我编写了一个函数,用于检查实时乐谱是否每隔0.1秒更改一次,以及是否在iPhone上播放系统声音。

- (void) checkIfShouldHaptic {
    loadedScore = [self loadScoreFromKey:keyScore];            //load score saved in key
    controllerScore = [self checkCurrentScore];                //check current score

    if (loadedScore < controllerScore){                        //if score in key is less than controller score
        [self saveScore:controllerScore];                      //save new score in key
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  //play system sound
        [self repeatCheckIfShouldHaptic];                      //repeat
    }
    else {                                                     //else score is not less
        [self repeatCheckIfShouldHaptic];                      //repeat
   }
}

- (void)repeatCheckIfShouldHaptic {
    [NSTimer scheduledTimerWithTimeInterval:timeDelayInSeconds target:self selector:@selector(checkIfShouldHaptic) userInfo:nil repeats:NO];
}

我的编程能力非常有限,所以我想知道是否有人可以告诉我是否以及如何对其进行优化?

我不确定一次又一次地调用自身的函数是否是好习惯,或者是否有更好的方法来重复检查。 谢谢。

2 个答案:

答案 0 :(得分:1)

我认为您可以使用KVO

@property NSUInteger score;

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self addObserver:self forKeyPath:@"score" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"From KVO");

    if([keyPath isEqualToString:@"score"])
    {
        id oldScore = [change objectForKey:NSKeyValueChangeOldKey];
        id newScore = [change objectForKey:NSKeyValueChangeNewKey];

        NSLog(@"%@ %@", oldScore, newScore);
    }
}

答案 1 :(得分:0)

我会稍微重写一下您的代码。恕我直言,使用NSTimer会比使用GCD消耗更多的资源。 如果您没有其他选择来接收某种通知,那么您的方法还不错。

- (void)checkIfShouldHaptic {
  loadedScore = [self loadScoreFromKey:keyScore];          //load score saved in key
  controllerScore = [self checkCurrentScore];              //check current score

  if (loadedScore < controllerScore){                      //if score in key is less than controller score
    [self saveScore:controllerScore];                      //save new score in key
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);  //play system sound
  }
  [self repeatCheckIfShouldHaptic];                      //repeat
}

- (void)repeatCheckIfShouldHaptic {
  __weak typeof(self) weakSelf = self;
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeDelayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [weakSelf checkIfShouldHaptic]
  });
}