gpt4 book ai didi

iphone - 澄清assign,retain,copy,strong?

转载 作者:太空狗 更新时间:2023-10-30 03:30:49 26 4
gpt4 key购买 nike

我对 Objective-C 还是个新手,在尝试找出设置属性时使用分配、保留、复制、强等的适当方法时遇到了一些困难。

例如,我声明了以下类型 - 我应该如何设置属性?

@property (nonatomic, ??) NSMutableArray *myArray
@property (nonatomic, ??) NSString *myString
@property (nonatomic, ??) UIColor *myColor
@property (nonatomic, ??) int *myIn
@property (nonatomic, ??) BOOL *myBOOL

谢谢....

最佳答案

重申一下,它确实取决于上下文。在非 ARC 情况下:

@property (nonatomic, copy) NSMutableArray *myArray
@property (nonatomic, copy) NSString *myString
@property (nonatomic, retain) UIColor *myColor
//Note the change to an int rather than a pointer to an int
@property (nonatomic, assign) int myInt
//Note the change to an int rather than a pointer to an int
@property (nonatomic, assign) BOOL myBOOL

myArray 上的副本是为了防止您设置的对象的另一个“所有者”进行修改。在 ARC 项目中,情况有些变化:

@property (nonatomic, copy) NSMutableArray *myArray
@property (nonatomic, copy) NSString *myString
@property (nonatomic, strong) UIColor *myColor
//Note the change to an int rather than a pointer to an int
@property (nonatomic, assign) int myInt
//Note the change to an int rather than a pointer to an int
@property (nonatomic, assign) BOOL myBOOL

在您的情况下,更改主要针对 myColor。您不会使用 retain,因为您没有直接管理引用计数。 strong 关键字是一种断言属性“所有权”的方式,类似于 retain。还提供了一个附加关键字,weak,通常用于代替对象类型的分配。 Apple 的 weak 属性的常见示例是针对委托(delegate)的。我建议通过 Transitioning to ARC Release Notes除了Memory Management Guide一两次,因为其中的细微差别比 SO 帖子中可以轻松涵盖的要多。

关于iphone - 澄清assign,retain,copy,strong?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9035658/

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