I. The internal implementation principle of attributes
Assign property Internal implementation
Setter Method:
// setter方法@property (nonatomicassignNSString *name;- (void)setName:(NSString *)name{ _name = name;}
Getter Method:
// getter方法- (NSString *)name{ return _name;}
What is the problem with observing the code below?
NSString *name = [[NSString alloc] initWithFormat:@”张三”];Person *p = [[Person alloc] init];[p setName:name];[name release];NSLog// 如果对象类型使用assign之后,会出现野指针异常[p release];
Retain Property internal implementation
Setter Method:
// setter方法@property (nonatomicNSString *name;- (void)setName:(NSString *)name{ if(_name != name) { [_name release]; _name = [name retain]; }}
Getter Method:
// getter方法- (NSString *)name{ return [[_name retain] autorelease];}
Property internal implementation of copy
Setter Method:
// setter?法@property (nonatomicNSString *name;- (void)setName:(NSString *)name{ if(_name != name) { [_name release]; _name = [name copy]; }}
Getter Method:
// getter方法- (NSString *)name{ return [[_name retain] autorelease];}
Second, release instance variable in Dealloc
Dealloc is NSObject? An instance method, corresponding to Alloc, used to reclaim the open memory space. This? method is automatically called by the system when the object reference count is 0 o'clock usually we release the instance variable of the class in Dealloc.
Dealloc use
With PERSON.M as an example, the code is as follows:
- (void)dealloc{ [_name release]; //释放setter?法泄露的实例变量 [super dealloc];}
Attention:
- Never move. Call Dealloc.
- The last of the Dealloc law must be written
[super dealloc];
.
Third, the principle of the realization of the convenient construction method
With PERSON.M as an example, the code is as follows:
+ (id)personWithName:(NSString *)name{ Person *p = [[Person alloc] initWithName:name]; return [p autorelease];}
return [p autorelease];
Is the most perfect solution to the case, neither memory leaks nor production of wild pointers.
Iv. Memory management of collection
Collection is Nsarray,nsdictionary,nsset ... such as Container class, collection will be self-management of internal elements.
Collection The memory of the manager , add collection in the object will be retain, remove the collection object will be released by Release,collection will release all objects inside.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Objective-c Learning Notes _ memory Management (ii)