我刚刚阅读了Craig Hockenberry关于ARC和副本的简短博客文章。 我现在的问题是,传递给分配给实例变量的初始值设定项的参数是否总是使用copy ? 或者它取决于实例变量的类型?
#import "MyObject.h" @implementation MyObject { SomeType *_ivar1; SomeOtherType *_ivar2; } -(id)initWithParam1:(SomeType *)param1 andParam2:(SomeOtherType *)param2 { if ((self == [super init])) { _ivar1 = [param1 copy]; // Always good _ivar2 = [param2 copy]; // practice? } return self; } @endI've just been reading a short blog post from Craig Hockenberry about ARC and copy. The question I now have is should parameters passed to initializers that are assigned to instance variables always use copy? Or does it depend on the type of the instance variable?
#import "MyObject.h" @implementation MyObject { SomeType *_ivar1; SomeOtherType *_ivar2; } -(id)initWithParam1:(SomeType *)param1 andParam2:(SomeOtherType *)param2 { if ((self == [super init])) { _ivar1 = [param1 copy]; // Always good _ivar2 = [param2 copy]; // practice? } return self; } @end最满意答案
取决于变量和意图的类型。
对于简单类型 - NSString,NSArray,NSNumber等... - 您使用副本,因为您通常希望存储的类型是不可变的。 也就是说,拥有firstName属性是没有意义的,外部的东西可以通过传入NSMutableString的实例来修改它。
对于更复杂的类 - 包含状态和功能的类 - 您通常不希望完全复制它,因为该状态可能随时间而变化。 例如,如果您的应用是具有播放封装在StreamingVideo实例中的视频的VideoPlayer实例的流式视频应用,则您不希望复制StreamingVideo,因为随着更多数据的下载,其内部状态将不断变化(或发生错误)。
即,当您需要状态的不可变快照时使用copy ,并且当您希望将对象A连接到B以便更改/监视/查询B的状态时使用引用。
而且,是的,你希望它是一致的。 如果属性是copy并且您有一个设置该属性的便利初始值设定项,请确保便利初始化程序还复制设置到该属性的任何内容。
Depends on the type of the variable and intent.
For simple types -- NSString, NSArray, NSNumber, etc... -- you use copy because you generally want the stored type to be immutable. I.e. it doesn't make sense to have a firstName property where something externally can modify it by passing in an instance of NSMutableString.
For more complex classes -- ones that encapsulate both state and functionality -- you generally do not want to copy it exactly because that state may be changing over time. For example, if your app were a streaming video app that had a VideoPlayer instance that played a video encapsulated in a StreamingVideo instance, you wouldn't want to copy the StreamingVideo as its internal state is constantly going to be changing as more data is downloaded (or an error occurs).
I.e. copy is used when you want an immutable snapshot of state and a reference is used when you want object A to be connected to B for purposes of changing/monitoring/querying B's state.
And, yes, you want it to be consistent. If a property is copy and you have a convenience initializer that sets that property, make sure the convenience initializer also copies whatever is set to the property.
更多推荐
发布评论