gpt4 book ai didi

objective-c - 使用@property(copy) 与@property(retain) 的经验法则是什么?

转载 作者:太空狗 更新时间:2023-10-30 03:57:57 27 4
gpt4 key购买 nike

我想知道在决定 ObjectiveC 中的给定属性应该是 retain 还是 copy 时,您是否遵循了经验法则?

你如何决定它应该是哪个?

最佳答案

通常你使用 copy 来保证安全,这些类有可变的变体,比如 NSStringNSArray,其他集合类,等等。看看为什么,考虑这里发生的事情......

从前,

@interface MyClass : NSObject
@property (retain) NSString *happyString;
- (void)rejoice;
@end

然后有一天,

- (void)bigBadMethod {
MyClass *myObject = [[[MyClass alloc] init] autorelease];
NSMutableString *theString = [NSMutableString stringWithString:@"I'm happy!"];
myObject.happyString = theString; // this is allowed because NSMutableString inherits from NSString
[myObject rejoice]; // prints "I'm happy!"

当突然...

    [theString setString:@"BRAAAAIIINNNSSSSS"];
[myObject rejoice]; // prints "BRAAAAIIINNNSSSSS"
}

你不会想要那样吧?所以如果你不想在你不看的时候发生变异,请使用 @property (copy)!

关于objective-c - 使用@property(copy) 与@property(retain) 的经验法则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7115337/

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