سؤال

Possible Duplicate:
With ARC why use @properties anymore?

NB: I actually don't think we can do away with properties, but I'm trying to understand the reasoning as to why not. :)

Referring back to this question, it seems like the principal reason we use properties is to avoid memory management issues. In other words, by creating a property we rid ourselves of the need to write out all these retain and release methods:

- (void) setOtherObj:(MyOtherObject *)anOtherObject {

    if (otherObject == anOtherObject) {
    return;  
    }

    MyOtherObject *oldOtherObject = otherObject; // keep a reference to the old value for a second
    otherObject = [anOtherObject retain]; // put the new value in  
    [oldOtherObject release]; // let go of the old object
} 

Since ARC deals with this now, could we not do away with properties all together and just set ivars by doing something like otherObject = anotherObject?

هل كانت مفيدة؟

المحلول

Memory management is one reason to use properties, but not the only one. You can only use plain instance variables within your own class, but not from outside. For that, you still need a property.

Properties don't even have to be backed by instance variables. For example, you might have a backgroundColor property in a view that actually returns and sets the backgroundColor property of some private subview. Or, say you have a readonly name property that actually doesn't correspond to an instance variable, but simply concatenates firstName and lastName.

Using properties instead of plain instance variable access also allows you to implement lazy initialization more easily, without having to change your code in a lot of places.

If you only use a property to handle memory management for you, you could do without it in a lot of cases now, but using a property still gives you more flexibility when you later decide that it shouldn't simply map to an instance variable.

نصائح أخرى

Avoiding memory issues was a very useful byproduct of properties. Their primary purpose remains access control (readonly vs. readwrite) and information hiding (i.e. logic behind getting and setting the property can change at any time with no change required to the users of your class). In addition, if you need the copy semantics, it is still available with the ARC.

ARC is to manage the memory-related-issues for you. Properties are a way to get/set values conveniently. So the arrival of ARC does not mean the end for properties.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top