apple cocoa内存管理笔记
2010-12-19 07:19:24 来源:WEB开发网下面的这种方式是不对的
Instance you don’t own is sent release- (void)reset {NSNumber *zero = [NSNumber numberWithInteger:0];创建的是一个autorelease的对象[self setCount:zero];[zero release];//这里释放是危险的}
When you add an object to a collection such as an array, dictionary, or set, the collection takes ownership of
it.在集合中增加object,那么这个object的所有者就变成了集合了
代码
// ...for (i = 0; i < 10; i++) {NSNumber *convenienceNumber = [NSNumber numberWithInteger:i];[array addObject:convenienceNumber];}//这种情况不需要releaseNSMutableArray *array;NSUInteger i;// ...for (i = 0; i < 10; i++) {NSNumber *allocedNumber = [[NSNumber alloc] initWithInteger: i];[array addObject:allocedNumber];[allocedNumber release];}//这种情况需要,此处只是将retain的计数减1而已
安全返回对象
下面两种方式是正确的
- (NSString *)fullName {
NSString *string = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
return string;
}
- (NSString *)fullName {
NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@", firstName,
lastName] autorelease];
return string;
}
相反,下面的方式是错误的- (NSString *)fullName {
NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@", firstName,
lastName] release];
return string;
}
同样,下面的方式也是错的- (NSString *)fullName {
NSString *string = [[NSString alloc] initWithFormat:@"%@ %@", firstName,
lastName];
return string;
}
对象拷贝机制
有两种实现拷贝协议的copyWithZone:方法的方式:
使用alloc and init..
使用 NSCopyObject.
看下面对象的定义
@interface Product : NSObject
{
NSString *productName;
float price;