在MRC环境下,假定CTRoom对象是CTPerson的一个成员变量,那么修改CTRoom对象时应注意,代码如下:
- (void) setRoom:(CTRoom *) room{ //需判断新旧值是否相等,一旦相等则[_room release]等价于[room release],那么[room retain]将抛出异常。 if(_room != room){ [_room release]; //释放旧值 _room = [room retain]; //retain新值 }}
- (void) dealloc
{
// [_room release];
// _room = nil;
self.room = nil; //同时,这一句代码等效前面两句
[super dealloc];]
}
CTPerson *person = [[CTPerson alloc] init]; CTRoom *r = [[CTRoom alloc] init]; [person setRoom:r]; [r release]; person.room = r; [person release];