performSelector may cause a leak because its selector is unknown

后端 未结 19 2247
小蘑菇
小蘑菇 2020-11-22 01:54

I\'m getting the following warning by the ARC compiler:

\"performSelector may cause a leak because its selector is unknown\".

Here\'s what

19条回答
  •  遥遥无期
    2020-11-22 02:52

    @c-road provides the right link with problem description here. Below you can see my example, when performSelector causes a memory leak.

    @interface Dummy : NSObject 
    @end
    
    @implementation Dummy
    
    - (id)copyWithZone:(NSZone *)zone {
      return [[Dummy alloc] init];
    }
    
    - (id)clone {
      return [[Dummy alloc] init];
    }
    
    @end
    
    void CopyDummy(Dummy *dummy) {
      __unused Dummy *dummyClone = [dummy copy];
    }
    
    void CloneDummy(Dummy *dummy) {
      __unused Dummy *dummyClone = [dummy clone];
    }
    
    void CopyDummyWithLeak(Dummy *dummy, SEL copySelector) {
      __unused Dummy *dummyClone = [dummy performSelector:copySelector];
    }
    
    void CloneDummyWithoutLeak(Dummy *dummy, SEL cloneSelector) {
      __unused Dummy *dummyClone = [dummy performSelector:cloneSelector];
    }
    
    int main(int argc, const char * argv[]) {
      @autoreleasepool {
        Dummy *dummy = [[Dummy alloc] init];
        for (;;) { @autoreleasepool {
          //CopyDummy(dummy);
          //CloneDummy(dummy);
          //CloneDummyWithoutLeak(dummy, @selector(clone));
          CopyDummyWithLeak(dummy, @selector(copy));
          [NSThread sleepForTimeInterval:1];
        }} 
      }
      return 0;
    }
    

    The only method, which causes memory leak in my example is CopyDummyWithLeak. The reason is that ARC doesn't know, that copySelector returns retained object.

    If you'll run Memory Leak Tool you can see the following picture: enter image description here ...and there are no memory leaks in any other case: enter image description here

提交回复
热议问题