apple cocoa内存管理笔记
2010-12-19 07:19:24 来源:WEB开发网id delegate;
}
@end
拷贝后的内存位置图如下:
假设从supercalass继承了NSCopying,但是父类没有实现NSCopying,那么你要实现的话必须拷贝super的实例,同样包括自己声明的变量。一般情况下安全的方式是使用如alloc,
init..., and set methods
另外一方面,如果super类已经实现了NSCopying,并且在你的类中你声明了一些实例变量,那么你必须实现copyWithZone:
如果类没有继承NSCopying的行为,那么实现copyWithZone: using alloc,init..., and set methods.下面是一个例子
- (id)copyWithZone:(NSZone *)zone
{
Product *copy = [[[self class] allocWithZone: zone]
initWithProductName:[self productName]
price:[self price]];
[copy setDelegate:[self delegate]];
return copy;
}
有些继承了NSCopying behavior的类,但是他们的super类的实现可能使用了 NSCopyObject function. NSCopyObject creates an exact shallow copy of an object
by copying instance variable values but not the data they point to. 举个例子, NSCell类采用如下的方式实现copyWithZone
- (id)copyWithZone:(NSZone *)zone
{
NSCell *cellCopy = NSCopyObject(self, 0, zone);
/* Assume that other initialization takes place here. */
cellCopy->image = nil;
[cellCopy setImage:[self image]];
return cellCopy;
}
在上面的实现采用的是浅拷贝
对可变长度的对象的拷贝实现 ,要继承NSMutableCopying
Core Foundation Objects in Cocoa中的内存管理
Core Foundation's memory allocation policy is that you need to release values returned by functions with “Copy” or “Create” in their name; you should not release values returned by functions that do not have “Copy” or “Create” in their name.
举几个例子
NSString *str = [[NSString alloc] initWithCharacters: ...]; ... [str release];
is equivalent to
更多精彩
赞助商链接