ARC 引入的属性有两个新的内存管理属性,strong
和 weak
。
除了copy
,这显然是完全不同的东西,strong
vs retain
和有什么不同吗?弱
vs assign
?
据我了解,这里唯一的区别是 weak
会将 nil
分配给指针,而 assign
不会,这意味着释放后,当我向指针发送消息时,程序将崩溃。但是如果我使用 weak
,这将永远不会发生,因为发送到 nil
的消息不会做任何事情。
我不知道 strong
和 retain
之间有什么区别。
我有什么理由应该在新项目中使用 assign
和 retain
,还是已经弃用了?
最佳答案
看了这么多Stackoverflow帖子和demo应用检查变量属性属性的文章,我决定把所有的属性信息放在一起:
下面是详细的文章链接,您可以在其中找到上述所有属性,这肯定会对您有所帮助。 非常感谢所有在这里给出最佳答案的人!
Variable property attributes or Modifiers in iOS
1.strong(iOS4 = 保留)
例子:
@property (strong, nonatomic) ViewController *viewController;
@synthesize viewController;
2.弱 -
例子:
@property (weak, nonatomic) IBOutlet UIButton *myButton;
@synthesize myButton;
强弱解释,Thanks to BJ Homer :
Imagine our object is a dog, and that the dog wants to run away (be deallocated).
Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached.
Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it.
As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out.
我们什么时候用弱?
你想使用weak的唯一一次是你想避免保留循环 (例如, parent 保留 child , child 保留 parent ,因此两者都不会被释放)。
3.retain = 强
例子:
@property (nonatomic, retain) NSString *name;
@synthesize name;
4.assign
例子:
@property (nonatomic, assign) NSString *address;
@synthesize address;
关于ios - Objective-C ARC : strong vs retain and weak vs assign,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8927727/
相关文章:
ios - 如何删除 UITableView 中的空单元格?
iphone - 按下时 UILongPressGestureRecognizer 被调用两次
objective-c - 如何在 Objective-C 中反转 NSArray?
objective-c - objectForKey 和 valueForKey 的区别?
objective-c - 在 Objective-C 中为类定义私有(private)方法的最佳方
iphone - 您在编写 Objective-C 和 Cocoa 时使用了哪些最佳实践?