复制vs强大的属性 [英] copy vs strong properties

查看:95
本文介绍了复制vs强大的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在iOS中比较新鲜,我想知道我们应该在属性中使用 copy ,例如

I am fresher in iOS and I want to know that when we should use copy in a property, e.g.

@property (nonatomic, retain) NSString* name;

vs

@property (nonatomic, copy) NSString* name;`

有什么区别保留复制,我何时应该使用一个而不是另一个?

What is the difference between retain and copy, and when should I use one but not the other?

推荐答案

@property (nonatomic, copy) NSString* name;

更好,因为 NSString 是不可变的,它的子类 NSMutableString 是可变的。

is better, as NSString is immutable and it's child class NSMutableString is mutable.

只要您使用 NSString 通过,你不会看到任何差异。但是当你开始使用 NSMutableString 时,事情就会变得有点冒险。

As long as you are using NSString through out, you won't see any difference. But when you start using NSMutableString, things can get little dicey.

NSMutableString *department = [[NSMutableString alloc] initWithString:@"Maths"];

Person *p1 = [Person new];
p1.department = department;

//Here If I play with department then it's not going to affect p1 as the property was copy
//e.g.
[department appendString:@"You're in English dept."];

如果它只是保留它会改变部门的p1
因此,在这种情况下,优先考虑复制。

Had it been just retain it would have changed the department of the p1. So having copy is prefered in this case.

这篇关于复制vs强大的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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