gpt4 book ai didi

objective-c - 初始化器和复制

转载 作者:太空狗 更新时间:2023-10-30 04:02:17 24 4
gpt4 key购买 nike

我刚刚阅读了一篇来自 Craig Hockenberry 的简短博文关于ARC and copy .我现在的问题是传递给分配给实例变量的初始值设定项的参数是否应该始终使用 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

最佳答案

我认为理解这篇文章的关键在于这句话:

Since I think it’s a bad idea to use accessors during -init the copy semantics defined by the @property are never used and ARC happily retains the reference instead of copying it.

我认为 Craig 是在专门谈论以下案例:

@interface MyObject : NSObject {
SomeType *_ivar1;
}
-(id)initWithParam1:(SomeType *)param1;
@property (copy, nonatomic) SomeType* prop1;
@end

@implementation MyObject
@synthesize prop1 = _ivar1;
-(id)initWithParam1:(SomeType *)param1 {
if ((self == [super init])) {
/*
Craig could have called

self.prop1 = param1;

but he believes that it's a bad idea to call accessors
from the initializer, so he calls copy explicitly.
*/
_ivar1 = [param1 copy];
}
return self;
}
@end

关于objective-c - 初始化器和复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11367600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com