简体   繁体   中英

Objective-C Property Keywords

OK - newbie Objective-C question:

When declaring properties there are attributes such as below:

@property (weak, nonatomic)

I realize I need read up on this to fully understand it but most of what I found was reference material, so a link to a good article that could explain best practices / usage scenarios (when to use which attribute for primitives, reference types, outlets, etc) or a couple of examples would be appreciated.

Thanks!

Even though it is waaaay to late for an answer i've found this question while googleing the same issue and also found this article by apple which explains the whole thing perfectly.

Hope it helps to anyone who are researching the same thing,

http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html

From a recent class I gave on this (inspired by Paul Hegarty)

nonatomic - NOT thread safe see link Justin pointed out in the comments above.

strong (or retain) - keep this object allocated until I don't point to it anymore (set it to nil). Compiler will also throw this out of the heap (deallocate it) if I am not pointed to strongly anymore (I get dealloc'd)

weak - keep this object allocated as long as something still points to it strongly. IBOutlets are usually declared as weak since they will be retained automatically by the view controller.

Primitive types are not allocated on the heap and don't use strong or weak

Atomicity has to do with threading, and is a pretty advanced topic for a newbie. The short answer, however, is that iOS properties are always declared as nonatomic. Here's some more detailed information about it.

The weak/strong keyword has to do with memory management with ARC and preventing what's called a retain cycle. This can also be a bit of a tough concept for a newbie, but the high-level overview is that a retain cycle happens when two objects have strong references to each other and thus neither object will be destroyed by ARC. This is a form of a memory leak, as you may have an object that's no longer in use but is still taking up memory. By declaring a property as weak, it will ensure that it's not automatically destroyed so long as something still has a strong reference to it. For instance, let's say you have an array with a couple of objects in it. Two of the objects have strong references to each other. Then, the array loses its owner and is destroyed. BUT, the two objects in that array that point to each other are NOT destroyed since they have strong references. Thus, you have two objects which you cannot access since the owning array is destroyed, but they're still taking up memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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