Car.h:
#import <Foundation/Foundation.h> @interface Card : NSObject @end
Car.m:
#import "Card.h" @implementation Card -(void)dealloc{ NSLog(@"Card被销毁"); [super dealloc]; } @end
Book.h:
#import <Foundation/Foundation.h> @interface Book : NSObject @end
Book.m:
#import "Book.h" @implementation Book -(void)dealloc{ NSLog(@"Book被销毁了"); } @end
Student.h:
#import <Foundation/Foundation.h> @class Book; @class Card; @interface Student : NSObject{ Book *_book; } //retain参数相当于.m中的setCard中的一大坨,nonatomic参数相当于set,get方法不需要枷锁,不需要线程保护,提高效率,一般都加nonatomic属性,以提高性能 @property(nonatomic,retain) Book *book; //retain参数相当于.m中的setCard中的一大坨 @property(retain) Card *card; //readonly是具有只读属性 还有readwrite属性 @property(readwrite) int age; //属性默认就是atomic属性,能够提供给多个线程调用,get和set方法进行枷锁,保证线程安全 @property(atomic) int no; //getter实现了方法名 @property(nonatomic,getter = isRich) BOOL rich; @end
Student.m:
#import "Student.h" #import "Book.h" @implementation Student //-(void)setBook:(Book *)book{ // if(_book!=book) // { // [_book release]; // _book=[_book retain]; // // } //} //setCard相当于.h之前@property(retain)参数 自动实现 //-(void)setCard:(Card *)card{ // if(_card!=card) // { // [_card release]; // _card=[_card retain]; // } //} //getf方法可以由系统自动帮助实现 //-(Book *)book{ // return _book; //} -(void)dealloc{ NSLog(@"Student被销毁"); [_book release]; [_card release]; [super dealloc]; } @end
main:
#import <Foundation/Foundation.h> #import "Student.h" #import "Book.h" #import "Card.h" int main(int argc, const char * argv[]) { @autoreleasepool { Student *student =[[Student alloc] init]; Book *book=[[Book alloc] init]; student.book=book; //student.rich=YES; //BOOL _rich=student.isRich;//前面Student.h中实现了getter方法名 Card *card=[[Card alloc] init]; [card release]; [book release]; [student release]; } return 0; }结果:
2013-08-02 15:03:12.496 内存管理3 @property参数[871:303] Card被销毁
2013-08-02 15:03:12.498 内存管理3 @property参数[871:303] Student被销毁
2013-08-02 15:03:12.499 内存管理3 @property参数[871:303] Book被销毁了
本文转自蓬莱仙羽51CTO博客,原文链接:http://blog.51cto.com/dingxiaowei/1366775,如需转载请自行联系原作者