Day13 oc autorelease

autorelease

The autorelease method will return the object itself. After the call, the object will be placed in the autorelease pool. When the autorelease pool is destroyed, a release operation will be performed on all objects in the pool.

Person *p = [[[Person alloc] init] autorelease];//The object counter has not changed

 After ios5.0, the use of automatic release pool

@autoreleasepool
{//Brackets begin to represent the creation of an automatic release pool
}//The end of parentheses means destruction

 which is

@autoreleasepool//Delays the release time of the object, and the disadvantage is that the destruction of the object cannot be precisely controlled
{//1
Person *p = [[[Person alloc] init] autorelease];
// Person *p = [[[[Person alloc] init] autorelease] autorelease]; After calling autorelease several times, the pool will do several release operations when it is released, so it will be released twice and an error will be reported
@autoreleasepool
{//2
//The management of the pool adopts the stack data structure (first in, last out), 1 is at the bottom of the stack, 2 is above 1
}
}

 ps: Do not use autorelease for objects that take up a lot of memory

Before ios5.0

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[pool release];

 The code generally encapsulates autorelease into class methods

@interface Person:NSObject
+(id)person;
@end


@implementation Person
+(id)person
{
return [[[self alloc] init] autorelease];//Be sure to use self to meet the needs of subclasses, do not use the class name directly
}
@end


when called
@autorelease
{
Person *p = [Person person];
}

Principles of use:

1. There are no alloc, new, and copy in the system's own methods, indicating that the returned objects are all autoreleased

2. Some class methods are often provided in development to quickly create autoreleased objects

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326892798&siteId=291194637