这个复制类方法是否会泄漏内存?

时间:2009-02-18 10:20:04

标签: objective-c cocoa memory-management memory-leaks properties

- (id)copyWithZone:(NSZone *)zone {
    PoolFacility *copy = [[[self class] allocWithZone:zone]init];
    copy.name = [self.name copy];
    copy.type = [self.type copy];
    copy.phoneNumber = [self.phoneNumber copy];
    //make sure I get proper copies of my dictionaries
    copy.address = [self.address mutableCopy];  
    copy.webAddress = [self.webAddress copy];
    copy.prices = [self.prices mutableCopy];
    copy.pools = [self.pools mutableCopy];
    return copy;
}

任何人都可以看到任何内存泄漏吗?

这是属性类型:

NSString *name;
NSString *type;
NSMutableDictionary *address;

NSString *phoneNumber;
NSString *webAddress;   

NSMutableArray *prices;
NSMutableArray *pools;

以下是属性声明:

@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *type;
@property (nonatomic, copy) NSString *phoneNumber;
@property (nonatomic, retain) NSMutableDictionary *address;
@property (nonatomic, copy) NSString *webAddress;
@property (nonatomic, retain) NSMutableArray *prices;
@property (nonatomic, retain) NSMutableArray *pools;

2 个答案:

答案 0 :(得分:7)

定义为复制而非保留的属性在设置如下(您的代码)时会有额外的副本

copy.name = [self.name copy];
copy.type = [self.type copy];
copy.phoneNumber = [self.phoneNumber copy];
copy.webAddress = [self.webAddress copy];

仅将它们写为

就足够了
copy.name = self.name;
copy.type = self.type;
copy.phoneNumber = self.phoneNumber;
copy.webAddress = self.webAddress;

答案 1 :(得分:1)

这几乎肯定像筛子一样泄漏。您需要提供@property和其他方法声明,以便我们推荐最佳解决方法。