A.内存存放、retain、release
1 //当一个Person对象被系统回收的时候,就会调用此方法 2 - (void) dealloc 3 { 4 NSLog(@"Person对象被回收"); 5 [superdealloc]; 6 }
1 //0 2 [prelease]; 3 4 p.age=11; 5 [prun];
1 @interfacePerson :NSObject 2 { 3 Book*_book; 4 } 5 6 - (Book*) book; 7 - (void) setBook:(Book*) book; 8 9 @end
1 @implementationPerson 2 - (Book*) book 3 { 4 return_book; 5 } 6 7 - (void) setBook:(Book*) book 8 { 9 if(_book!= book) 10 { 11 [_bookrelease]; 12 } 13 _book= [bookretain]; 14 } 15 16 - (void) dealloc 17 { 18 [_bookrelease]; 19 NSLog(@"Person被回收"); 20 [superdealloc]; 21 } 22 23 @end
1 intmain(intargc,constchar* argv[]) { 2 // b=1 3 Book*b = [[Bookalloc]init]; 4 // p1=1 5 Person*p1 = [[Personalloc]init]; 6 7 // b=2 8 [p1setBook:b]; 9 10 // b=1 11 [brelease]; 12 b =nil; 13 14 // p1=0, b=0 15 [p1release]; 16 p1 =nil; 17 18 return0; 19 }
1 @interfacePerson :NSObject 2 @propertyintage; 3 @property(retain)Book*book; 4 5 @end
1 @implementationPerson 2 - (void) dealloc 3 { 4 [_bookrelease]; 5 [superdealloc]; 6 } 7 @end
1 #import<Foundation/Foundation.h> 2 #import"Card.h" 3 4 @interfacePerson : NSObject 5 @property(nonatomic,retain) Card *card; 6 @end
1 #import<Foundation/Foundation.h> 2 #import"Person.h" 3 4 @interfaceCard :NSObject 5 @property(nonatomic,retain)Person*person; 6 @end
1 #import<Foundation/Foundation.h> 2 3 @classCard; 4 5 @interfacePerson :NSObject 6 @property(nonatomic,retain)Card*card; 7 @end
1 #import<Foundation/Foundation.h> 2 3 @classPerson; 4 5 @interfaceCard : NSObject 6 @property(nonatomic,retain) Person *person; 7 @end
1 intmain(intargc,constchar* argv[]) { 2 Person*p = [[Personalloc]init]; 3 Card*c = [[Cardalloc]init]; 4 p.card= c; 5 c.person= p; 6 7 [prelease]; 8 [crelease]; 9 return0; 10 }
1 @implementationPerson 2 - (void) dealloc 3 { 4 NSLog(@"Person被回收"); 5 [_cardrelease]; 6 [superdealloc]; 7 } 8 9 @end
1 #import<Foundation/Foundation.h> 2 3 @classPerson; 4 5 @interfaceCard :NSObject 6 @property(nonatomic,assign)Person*person; 7 @end
1 @implementationPerson 2 - (void) dealloc 3 { 4 NSLog(@"Person被回收"); 5 [_cardrelease]; 6 [superdealloc]; 7 } 8 9 @end
1 @implementationCard 2 - (void) dealloc 3 { 4 NSLog(@"Card被回收"); 5 // [_person release]; //没有retain,不必release 6 [superdealloc]; 7 } 8 9 @end
1 2 Person*p =nil; 3 4 //创建自动释放池 5 @autoreleasepool 6 {//自动释放池开始 7 // autorelease方法会返回对象本身 8 // autorelease会将对象放到一个自动释放池 9 //当自动释放池被销毁的时候,会对池子里面的所有对象做一次release操作 10 p = [[[Personalloc]init]autorelease]; 11 12 p.age=10; 13 14 }//自动释放池销毁,所有对象release一次 15 16 // p.age = 20; //运行时错误
1 + (id) person 2 { 3 return[[[Personalloc]init]autorelease]; 4 }
1 + (id) person 2 { 3 return[[[selfalloc]init]autorelease]; 4 }