简体   繁体   English

使用@property和'copy'属性分配NSMutableArray

[英]assign NSMutableArray with @property and 'copy' attribute

I'm following an official tutorial Your second iOS App:Storyboard and it told me to declare a property masterBirdSightingList like this(just a specific example and not necessary to know the context) : 我正在关注官方教程你的第二个iOS应用程序:Storyboard ,它告诉我像这样声明一个属性masterBirdSightingList (只是一个特定的例子,不需要知道上下文):

@property (nonatomic, copy) NSMutableArray *masterBirdSightingList;

Note that there's an attribute copy . 请注意,有一个属性副本 and then synthesize this property : 然后合成这个属性:

@synthesize masterBirdSightingList = _masterBirdSightingList;

And next there's one init method which made me confused : 接下来有一个让我困惑的init方法:

- (void)initializeDefaultDataList {
NSMutableArray *sightingList = [[NSMutableArray alloc] init];
self.masterBirdSightingList = sightingList;
[self addBirdSightingWithName:@"Pigeon" location:@"Everywhere"];
}

Definitely sightingList is allocated for spaces and then it's assigned to the masterBirdSightingList property. 绝对是为空格分配了sightingList,然后将它分配给masterBirdSightingList属性。 The property has a copy attribute, though. 但是,该属性具有复制属性。 it means the instance variable _masterBirdSightingList would be allocated for another space to preserve stuffs from sightingList . 这意味着实例变量_masterBirdSightingList将为另一个空间,从sightingList保存的东西进行分配。 Why? 为什么? Why not directly allocate space for the property like this : 为什么不直接为属性分配空间,如下所示:

self.masterBirdSightingList = [[NSMutableArray alloc] init];

In Objective-C, the copy attribute in a property means the setter synthesized will look like this: 在Objective-C中,属性中的copy属性意味着合成的setter将如下所示:

-(void)setMasterBirdSightingList:(NSMutableArray*)newValue
{
    if (_masterBirdSightingList == newValue) return;
//  NSMutableArray* oldValue = _masterBirdSightingList;
    _masterBirdSightingList = [newValue copy];
//  [oldValue release];    // <-- not applicable in ARC.
}

and that dot syntax will always be translated to 并且点语法将始终转换为

[self setMasterBirdSightingList:sightingList];

regardless of the attribute of the property. 无论属性的属性如何。

The "allocated for another space to preserve stuffs from sightingList" stuff is done via the -copy method. “分配给另一个空间来保存来自sightingList的东西”的东西是通过-copy方法完成的。 The way you pass the argument to the setter's newValue parameter is irrelevant. 将参数传递给setter的newValue参数的方式无关紧要。


Edit : As @David mentioned in the comment, the -copy method of a mutable type returns an immutable object. 编辑 :正如注释中提到的@David一样 ,可变类型的-copy方法返回一个不可变对象。 You have to override the setter to call -mutableCopy instead. 您必须覆盖setter才能调用-mutableCopy See What's the best way to use Obj-C 2.0 Properties with mutable objects, such as NSMutableArray? 请参阅使用可变对象的Obj-C 2.0属性的最佳方法是什么,例如NSMutableArray? .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM