Objective C - ARC - When to use @autoreleasepool

元气小坏坏 提交于 2019-12-02 23:39:43
Bryan Chen

by line

c = nil; //Forces a release

a Customer instance is deallocated because no one is retaining it, so as a result the output is

Destroying: Johnny Walker

but n and a have not been deallocated because they still remain in the scope and nil has not been assigned to them.

and I don't think this is any kind of memory leak


you normally do not need to use @autorelasepool unless you are doing something like this

- (void)myMethod {
    for (int i = 0; i < 1000000; i++) {
        NSString *string = [NSString stringWithFormat:@"%d", i];
        // do something with string
    }
}

Than 1000000 NSString will be allocated during loop. They will be deallocated after the method returned (actually after this runloop) but already consume too much memory. Therefore should replace to

- (void)myMethod {
    for (int i = 0; i < 1000000; i++) {
        @autoreleasepool {
            NSString *string = [NSString stringWithFormat:@"%d", i];
            // do something with string
        }
    }
}

you should read this to learn more about memory management https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html#//apple_ref/doc/uid/20000047-CJBFBEDI

Odd-Arne Dahle

The obvious differense between name and address is that you create an Address Object for address and NSString for name. In the address object it is @public. This meeas the NSString is out of scope when customer is released, but not the address object, it will still remember the address given to the @public NSString *city when you release customer.

So when you call this public value for address it is still there, but not the NSString for name. To fix this you either remove the interface of Address Object, which releases both values or you create one interface for name instead of using NSString.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!