简体   繁体   English

弱和分配属性之间的差异?

[英]differences between weak and assign property?

I have few questions. 我几乎没有问题。

1)where assign property will take memory as we dont need to release for reducing reference count? 1)其中assign属性将占用内存,因为我们不需要释放以减​​少引用计数?

2)what is the difference between auto zero reference and non-auto zero reference?how does it work? 2)自动归零参考和非自动归零参考有什么区别?它是如何工作的? how will take memory? 怎么会记忆?

weak applies to objects (they have reference counts and all the stuff), but weak references don't increase refcount. weak适用于对象(它们具有引用计数和所有内容),但弱引用不会增加引用计数。 But once the object is deallocated (from anywhere in the code), any weak reference to that object is set to nil . 但是一旦对象被释放(从代码中的任何位置),对该对象的任何弱引用都将设置为nil This is extremely useful, because if you use only strong and weak references, you can't end up with an invalid pointer (pointer to an already deallocated object). 这非常有用,因为如果仅使用强引用和弱引用,则无法使用无效指针(指向已解除分配的对象的指针)。

assign does absolutely nothing with the reference, it is usually used for ints, floats and other non-object types. assign对引用绝对没有任何作用,它通常用于int,float和其他非对象类型。 You can of course assign an object reference to such a variable, but if the object is deallocated, you will still have a pointer to it's memory (which is garbage now, and will hurt you when you use it). 您当然可以为这样的变量分配一个对象引用,但是如果该对象被释放,您仍然会有一个指向它的内存的指针(现在它是垃圾,当你使用它时会伤害你)。

Your concerns about "memory use" are weird - references don't take memory, object do. 你对“内存使用”的担忧很奇怪 - 引用不占用内存,对象也不行。 But you can't deallocate an object if you are going to use it. 但是如果要使用它,则无法释放对象。 The simple rule for beginners is: for objects, use strong references whenever you can. 初学者的简单规则是:对于对象,尽可能使用强引用。 When you have a reason not to use strong reference, use weak (usually for delegates and datasources). 当您有理由不使用强引用时,请使用weak(通常用于委托和数据源)。 For primitive types (int, float, CGRect, ...) use assign, because they are not objects. 对于原始类型(int,float,CGRect,...),请使用assign,因为它们不是对象。

assign is like weak but there's no zeroing of the pointer when it leaves the heap. assign就像weak但是当它离开堆时指针没有归零。 So, it's not as safe as weak . 所以,它并不像weak那样安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM