标签:内存管理 objective-c ios set方法
1 alloc和release成对出现@interface Book { int _price; } - (void)setPrice:(int)price; - (int)price; @end
@implementation Book - (void)setPrice:(int)price { _price = price; } - (int)price { return _price; } - (void)dealloc { [_book release]; _book = nil; [super dealloc]; } @end
@interface Person { Book* _book; } - (void)setBook:(Book*)book; - (Book*)book; @end
@implementation Person - (void)setBook:(Book*)book { // retain新的,release旧的,把新的赋给旧的 if (_book != book){ [book retain]; [_book release]; _book = book; } /* 可以简写为: if (_book != book){ [_book release]; _book = [book retain]; } */ } - (Book*)book { return _book; } @end
#import <Foundation/Foundation.h> int main() { Person* person = [[Person alloc] init]; Book* book = [[Book alloc] init]; [person setBook:book]; [book release]; book = nil; [person release]; return 0; }
标签:内存管理 objective-c ios set方法
原文地址:http://blog.csdn.net/xufeng0991/article/details/43269741