ARC memory leaks

前端 未结 2 1277
春和景丽
春和景丽 2020-11-30 03:21

I am experiencing memory leaks linked to NSMutableArray\'s in a project configured to use ARC, which I thought was supposed to handle these things for you.

The follo

相关标签:
2条回答
  • 2020-11-30 03:53

    Very likely you have defined the NSMutableArray as a static variable. When you do that, you fall outside the bounds of any autorelease pool, since static definitions are activated outside of any runloop. ARC is not magically, it simply automates memory management calls within the framework of the existing retain/release framework and so cannot help in those cases.

    The solution is to initialize the static variable somewhere in a class so that your mutable array is built within the runloop.

    0 讨论(0)
  • 2020-11-30 04:10

    You're probably running this code on a background thread, and don't have an autorelease pool in place. ARC will still autorelease objects for you on occasion, and if you're calling into Apple frameworks, they may still be non-ARC, so they definitely could be autoreleasing objects for you. So you still need an autorelease pool in place.

    Cocoa creates an autorelease pool for you on the main thread, but doesn't do anything for you on background threads. If you're going to kick something off onto a background thread without using NSOperation or something, you'll want to wrap that thread in an @autoreleasepool, like so:

    - (void)doSomething {
        [self performSelectorInBackground:@selector(backgroundSomething)];
    }
    
    - (void)backgroundSomething {
        @autoreleasepool {
            NSLog(@"Here I am in the background, doing something.");
            myArray = [[NSMutableArray alloc] init];
            // etc.
        }
    }
    
    0 讨论(0)
提交回复
热议问题