//// Person.h#import#import "Room.h"#import "Car.h"#import "Dog.h"@interface Person : NSObject{ Room *_room; Car *_car; Dog *_dog;}/*- (void)setRoom:(Room *)room;- (void)setCar:(Car *)car;- (void)setDog:(Dog *)dog;- (Room *)room;- (Car *)car;- (Dog *)dog; */@property(nonatomic, retain) Room *room;//标准写法都是(nonatomic, retain)/* 写了retain就可以生成: - (void)setRoom:(Room *)room { // 1.判断传入的对象和当前对象是否一样 if (_room != room) { // 2.release以前的对象 [_room release]; // 3.retain传入的对象 _room = [room retain]; } } *//* readonly: 只会生成getter方法 readwrite: 既会生成getter也会生成setter, 默认什么都不写就是readwrite getter: 可以给生成的getter方法起一个名称 setter: 可以给生成的setter方法起一个名称 retain: 就会自动帮我们生成getter/setter方法内存管理的代码,上次44,45的内容 assign: 不会帮我们生成set方法内存管理的代码, 仅仅只会生成普通的getter/setter方法, 默认什么都不写就是assign。 多线程 atomic :性能低(默认) nonatomic :性能高 在iOS开发中99.99%都是写nonatomic,因为手机性能低。 atomic用于pc开发中。*/@end
//// Person.m#import "Person.h"@implementation Person/*- (void)setRoom:(Room *)room{ // 1.判断传入的对象和当前对象是否一样 if (_room != room) { // 2.release以前的对象 [_room release]; // 3.retain传入的对象 _room = [room retain]; }}- (void)setCar:(Car *)car{ if (_car != car) { [_car release]; _car = [car retain]; }}- (void)setDog:(Dog *)dog{ if (_dog != dog) { [_dog release]; _dog = [dog retain]; }}- (Room *)room{ return _room;}- (Car *)car{ return _car;}- (Dog *)dog{ return _dog;} */- (void)dealloc{ [_room release]; [_car release]; [_dog release]; NSLog(@"%s", __func__); [super dealloc];}@end
//// main.m// property修饰符#import#import "Person.h"int main(int argc, const char * argv[]) { Person *p = [Person new]; Room *r = [Room new]; /*// Car *c =[Car new];// Dog *d = [Dog new]; // p.room = r;// p.car = c;// p.dog = d; // [d release];// [c release];// [r release];// [p release]; */ p.room = r; [r release]; // 换房了, 如果set方法中没有release旧值, 就会内存泄露 Room *r2 = [Room new]; p.room = r2; [r2 release]; // 重复赋值 p.room = r; [p release]; return 0;}