初始化器和副本(Initializers and copy)

编程入门 行业动态 更新时间:2024-10-25 02:20:57
初始化器和副本(Initializers and copy)

我刚刚阅读了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; } @end

I'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.

更多推荐

本文发布于:2023-07-27 17:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293603.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:副本   初始化   copy   Initializers

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!