一、retain屬性的主要作用
1、O-C記憶體管理和點文法
1>OC記憶體管理正常情況要使用大量的retain和relrese操作
2>點文法可以減少使用retain和release的操作
二、@property(retain)編譯器如何申明
編譯器對於@property中的retain展開是不一樣的
主要是要釋放上一次的值,增加本次計數器
在dog.h中聲明的:
@property(retain)Dog *dog;
展開後為:
-(void) setDog:(Dog *)aDog;
-(Dog *)dog;
三、@synthesize編譯器如何?展開
在dog.m中實現:
@synthesize dog=_dog;
展開後為:
-(void) setDog:(Dog *)aDog{
if(_dog!=aDog){
[_dog release];
_dog=[aDog retain];
}
}
-(Dog *)dog{
return _dog;
}
四、dealloc需要注意內容
dealloc必須要釋放dog(retain)
在dog.m中
-(void) dealloc
{
self.dog=nil;
[super dealloc];
}
五、copy屬性的主要作用
copy屬性是完全把對象重新拷貝了一份,計數器從新設定為1,和之前拷貝的資料完全脫離關係。
@property(copy) NSString* str;
//表示屬性的getter函數
-(double) str
{
return str;
}
//表示屬性的setter函數
-(void) setStr:(NSString *)newStr
{
str=[newStr copy];
}
六、assign,retain,copy
1、foo=value;//簡單的引用賦值
2、foo=[value retain];//引用賦值,並且增加value的計數器
3、foo=[value copy];//將value複製了一份給foo,複製後,foo和value就毫無關係
Person.h中的代碼
View Code
#import <Foundation/Foundation.h>#import "Dog.h"@interface Person : NSObject{ Dog *_dog;}//- (void) setDog:(Dog *)aDog;//- (Dog *) dog;@property (retain) Dog *dog;@end
Person.m
View Code
#import "Person.h"@implementation Person@synthesize dog = _dog;//- (void) setDog:(Dog *)aDog//{// if (aDog != _dog) {// [_dog release];// // _dog = [aDog retain];// //讓_dog技術器 +1// }//}//- (Dog *) dog//{// return _dog;//}- (void) dealloc{ NSLog(@"person is dealloc"); // 把人擁有的_dog釋放 //[_dog release], _dog = nil; self.dog = nil; //[self setDog:nil]; [super dealloc];}@end
Dog.h
View Code
#import <Foundation/Foundation.h>@interface Dog : NSObject{ int _ID;}@property int ID;@end
Dog.m
View Code
#import "Dog.h"@implementation Dog@synthesize ID = _ID;- (void) dealloc{ NSLog(@"dog %d is dealloc", _ID); [super dealloc];}@end
main.m
View Code
#import <Foundation/Foundation.h>#import "Person.h"#import "Dog.h"// Person// Dog.// Person Dog.int main (int argc, const char * argv[]){ @autoreleasepool { NSLog(@"Hello, World!"); Dog *dog1 = [[Dog alloc] init]; [dog1 setID:1]; Dog *dog2 = [[Dog alloc] init]; [dog2 setID:2]; Person *xiaoLi = [[Person alloc] init]; [xiaoLi setDog:dog1]; [xiaoLi setDog:dog2]; [dog1 release]; [xiaoLi release]; [dog2 release]; #if 0 Dog *dog1 = [[Dog alloc] init]; [dog1 setID:1]; Person *xiaoLi = [[Person alloc] init]; // 小麗要遛狗 [xiaoLi setDog:dog1]; Person *xiaoWang = [[Person alloc] init]; [xiaoWang setDog:dog1]; NSLog(@"dog1 retain count is %ld", [dog1 retainCount]); // dog1 retain count is 3 [dog1 release]; NSLog(@"dog1 retain count2 is %ld", [dog1 retainCount]); // dog1 retain count2 is 2 [xiaoWang release]; NSLog(@"dog1 retain count3 is %ld", [dog1 retainCount]); // person is dealloc // dog1 retain count3 is 1 [xiaoLi release]; // person is dealloc // dog 1 is dealloc#endif } return 0;}