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

为什么我在NSTimer选择器中获得EXC\u BAD\u访问权限?

  •  1
  • Sauleil  · 技术社区  · 16 年前

    我有个很奇怪的问题。简而言之,我将编写一些伪代码:

    init: create a dictionary and insert n elements.
          create a "repeat timer" and add it to the currentRunLoop using the timerRefresh selector.
    
    timerRefresh: using a list of keys, find the items in the dictionary
                  if the item exists -> call a function
    

    所以,不知什么原因,当我这样做时,我得到了一个EXC\u BAD\u访问权限:

        [item function];
    

    所以,我想知道是否有线程问题?或者其他一些模糊的东西?

    调用堆栈非常简单:

    #0  0x93e0604b in objc_msgSend_fpret
    #1  0x00f3e6b0 in ??
    #2  0x0001cfca in -[myObject timerRefresh:] at myObject.m:000
    #3  0x305355cd in __NSFireTimer
    #4  0x302454a0 in CFRunLoopRunSpecific
    #5  0x30244628 in CFRunLoopRunInMode
    #6  0x32044c31 in GSEventRunModal
    #7  0x32044cf6 in GSEventRun
    #8  0x309021ee in UIApplicationMain
    #9  0x000027e0 in main at main.m:14
    

    所以,如果您有任何建议,我们将不胜感激。

    @劳伦特:这是我重写实际值以匹配我的示例的一个输入错误(固定的)

    @杰里米:我会试着发布一些代码来帮助你。代码已简化。

    定时器初始化+刷新功能:

    _refreshTimer = [[NSTimer alloc] initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:5] interval:5
                                     target:self selector:@selector(onTimerRefresh:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_refreshTimer forMode:NSDefaultRunLoopMode];
    
    //...
    
     (void)onTimerRefresh:(NSTimer*)theTimer {
          // the actual code is here. I will rewrite it so it's simpler:
         for (MyKey key in keys) {
             MyObject* object = [dictionary objectForKey:key];
             if (object)
                 [object function];
         }
     }
    

    我希望它更清楚一点。

    ---编辑#2---

    @你说得对,我犯了个大错。它应该是计时器方法,而不是函数。我只是把它修好。对不起,弄错了。但仅供参考,方法签名是:

    - (bool)update;
    
    1 回复  |  直到 16 年前
        1
  •  0
  •   Sauleil    16 年前

    我想我终于找到问题所在了。在“更新”方法中

    - (bool)update {
        // ...
        NSDate* now = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval interval = [now timeIntervalSinceNow] - [creation timeIntervalSinceNow];
        //...
    }
    

    问题是我没有在init中保留日期(创建)。我真的不明白为什么对象被“损坏”,但我认为调试器应该指向那个变量而不是函数调用。。。

    我会让应用程序运行一段时间,看看崩溃是否消失。