【问题标题】:(iphone) nsInvocation leaks .. maybe the passed arguments?(iphone) nsInvocation 泄漏.. 可能是传递的参数?
【发布时间】:2011-01-14 04:26:12
【问题描述】:

我正在后台线程上调用选择器,
选择器周围有 NSAutorelasePool。
我猜我传递给选择器的参数导致了问题。 我该如何处理?

  SEL theSelector;
    NSMethodSignature *aSignature;
    NSInvocation *anInvocation;

    theSelector = @selector(changeColor:forColorString:);
    aSignature = [[animationData class] instanceMethodSignatureForSelector:theSelector];
    anInvocation = [NSInvocation invocationWithMethodSignature:aSignature];
    [anInvocation setSelector:theSelector];
    [anInvocation setTarget:animationData];
    // indexes for arguments start at 2, 0 = self, 1 = _cmd                                                                                                                                                                                                                   
    [anInvocation setArgument:&currentColor atIndex:2];
    [anInvocation setArgument:&nsColorString atIndex:3];

    [anInvocation performSelectorInBackground:@selector(invoke) withObject:NULL];

【问题讨论】:

    标签: iphone multithreading memory-leaks nsinvocation


    【解决方案1】:

    当您告诉调用在后台执行调用时,将创建新线程,调用是第一个调用的方法。 Invoke 不会创建自动释放池,因此在该方法期间自动释放的任何内容都会泄露。

    要解决此问题,请使用包装方法来执行调用。

    - (void)performInvocation:(NSInvocation *)anInvocation {
        NSAutoreleasePool *pool = [NSAutoreleasePool new];
        [anInvocation invoke];
        [pool release];
    }
    
    //where you were performing the invoke before:
    [self performSelectorInBackground:@selector(performInvocation:) withObject:anInvocation];
    

    【讨论】:

    • 谢谢,它和用池包装选择器一样吗? -(void) theSelectorToPerform { NSAutoreleasePool * pool = [NSAutoreleasePool new]; .. 选择器代码 ... [池释放]; } ?
    【解决方案2】:

    除了ughoavgfhw所说的,如果你打算将对象设置为参数并传递给后台线程,你还需要调用[anInvocation retainArguments]。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 2011-01-16
      • 2012-08-19
      • 2017-09-23
      • 2011-08-12
      • 1970-01-01
      • 2013-08-04
      相关资源
      最近更新 更多