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

Dan*_*gan 2 cocoa memory-leaks memory-management properties objective-c

- (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;
}
Run Code Online (Sandbox Code Playgroud)

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

这是属性类型:

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

NSString *phoneNumber;
NSString *webAddress;   

NSMutableArray *prices;
NSMutableArray *pools;
Run Code Online (Sandbox Code Playgroud)

以下是属性声明:

@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;
Run Code Online (Sandbox Code Playgroud)

epa*_*tel 7

定义为copy并且不保留的属性在设置如下时会有一个额外的副本(您的代码)

copy.name = [self.name copy];
copy.type = [self.type copy];
copy.phoneNumber = [self.phoneNumber copy];
copy.webAddress = [self.webAddress copy];
Run Code Online (Sandbox Code Playgroud)

仅将它们写为是足够的

copy.name = self.name;
copy.type = self.type;
copy.phoneNumber = self.phoneNumber;
copy.webAddress = self.webAddress;
Run Code Online (Sandbox Code Playgroud)

  • "@property(...,copy)"表示使用点表示法时会创建副本.之前的值将发送一个版本. (2认同)