gpt4 book ai didi

objective-c - 这个复制类方法会泄漏内存吗?

转载 作者:行者123 更新时间:2023-12-03 16:25:05 25 4
gpt4 key购买 nike

- (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;

最佳答案

定义为复制而不是保留的属性在设置如下(您的代码)时将有一个额外的副本

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;

关于objective-c - 这个复制类方法会泄漏内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/560507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com