1

I am currently learning about memory management and properties in Objective-C. I recently read through this post and answers to my previous question concerning how @property and @synthesize work in Objective-C. This has clarified things somewhat.

It seems like the point is to distinguish between local variables and member variables in terms of memory management, but I'm still not totally clear on the subject.

If I have:

@interface FooClass : NSObject {
     NSObject *bar_;    
}

why do I need to create the property? I mean, I understand that the property creates getters and setters, but so what? I have my instance variable bar_ which I can set using foo.bar_ = newObject;. What advantages does it give me to have a property called bar and then setting bar_ using foo.bar = newObject?

Community
  • 1
  • 1
Eric Brotto
  • 53,471
  • 32
  • 129
  • 174

3 Answers3

1

First of all, for accessing an instance variable you can't use

foo.bar_ = newObject;

you need to use

foo->bar_ = newObject;

(of course, bar_ i-var must be declared as public one, if you don't want to get a compiler error)

If assigning objects like above, you'll be forced to add memory-management related code (in non-ARC project) with every assignment - that will result in increased code complexity.

Another reason for using properties, overriding a setter or getter will allow you to perform custom actions on assignment or resolving a value.

But the main reason here, if you're not familiar with OOP principles - abstraction. Your class users must not know, how your class is implemented internally, or you'll get too many hard dependencies in your code. And it will be really difficult to separate out, update or support something.

Denis
  • 6,313
  • 1
  • 28
  • 27
0

You cannot set bar_ using foo.bar_ without creating a setter because, in Objective-C, dot-syntax actually calls the setter method.

Besides, usually bar_ it's private, so you cannot access it directly from outside your class.

Creating a property will automatically create getter/setter methods; besides it will take care also of memory issues (according to the parameters you specify when creating the property, like retain, copy, assign and so on).

Manlio
  • 10,768
  • 9
  • 50
  • 79
0

Getters/Setters encapsulate the ivars and take care of memory management, concurrent access (non atomic ..) etc. Things like KVO depend on conventions like getter/setters.

hburde
  • 1,441
  • 11
  • 6