使用@property(copy)与@property(retain)的经验法则是什么? [英] What is the rule of thumb for using @property(copy) vs. @property(retain)?

查看:105
本文介绍了使用@property(copy)与@property(retain)的经验法则是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wonder if there is a rule of thumb you follow, when deciding whether or not a given property in ObjectiveC should be a retain or copy?

您如何确定应该是哪个?

How do you decide which it should be?

推荐答案

通常,为了安全起见,将copy用于具有可变变体的类,例如NSStringNSArray,其他集合类等.为什么,考虑这里发生了什么...

Typically you use copy for safety with classes which have mutable variants, like NSString, NSArray, the other collection classes, etc. To see why, consider what happens here...

从前,

@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)

And you wouldn't want that, would you? So use @property (copy) if you don't want to get mutated while you're not looking!

这篇关于使用@property(copy)与@property(retain)的经验法则是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆