代码之家  ›  专栏  ›  技术社区  ›  Reanimation

优化在Objc中调用它自己的函数

  •  0
  • Reanimation  · 技术社区  · 6 年前

    我已经编写了一个函数来检查实时评分是否每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 回复  |  直到 6 年前
        1
  •  0
  •   Serj Kultenko    6 年前

    我会重写你的代码一点。使用nstimer的imho比使用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]
      });
    }
    
        2
  •  1
  •   9to5ios    6 年前

    我想你可以用 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);
        }
    }