NSTimer Category + Blocks implementation to replace selector

后端 未结 3 687
清歌不尽
清歌不尽 2021-01-06 20:16

I am quite new to blocks and objective-c, and i am trying to write my first category using both. My idea is to create a category on NSTimer that will receive a block as a pa

3条回答
  •  暖寄归人
    2021-01-06 21:04

    This should work:

    NSTimer* timer = [[NSTimer alloc] initWithFireDate:[NSDate date] 
                                              interval:theSeconds
                                                target:timer
                                              selector:@selector(theBlock) 
                                              userInfo:nil 
                                               repeats:repeats];
    

    The problem is that you're setting the target of the new NSTimer instance to be self. However, in the context of + scheduleTimerWithTimeInterval:repeats:actions: (notice the +), self is NSTimer, and not (as you probably thought) your newly-created NSTimer instance.

    As you can see from the error message, your app is crashing because NSTimer doesn't respond to the class method + theBlock, which is of course correct since you only defined the instance method - theBlock.

提交回复
热议问题