Memory management and performSelectorInBackground:

前端 未结 2 1338
我寻月下人不归
我寻月下人不归 2020-12-13 07:58

Which is right? This:

NSArray* foo = [[NSArray alloc] initWithObjects:@\"a\", @\"b\", nil];
[bar performSelectorInBackground:@selector(baz:) withObject:foo];         


        
相关标签:
2条回答
  • 2020-12-13 08:16

    First is wrong.

    performSelectorInBackground:withObject: retains both bar and foo until task is performed. Thus, you should autorelease foo when you create it and let performSelectorInBackground:withObject take care of the rest. See documentation

    Latter is correct because you autorelease foo when you create it. Autorelease pool that you create inside baz has nothing do with correctness of foo's memory management. That autorelease pool is needed for autoreleased objects inside pool allocation and release in baz, it doesn't touch foo's retain count at all.

    0 讨论(0)
  • 2020-12-13 08:28

    The correct approach now would in fact be to do:

    NSArray* foo = [[[NSArray alloc] initWithObjects:@"a", @"b", nil] autorelease];
    [bar performSelectorInBackground:@selector(baz:) withObject:foo];
    
    - (void)baz:(NSArray*)foo {
        @autoreleasepool {
            ...
        }
    }
    
    0 讨论(0)
提交回复
热议问题