1

I have some instance variables in my class that I'd want to be accessible anywhere. Like so:

@interface SomeObject : NSObject
{
    @public
        NSString *someString;
}
@end

@implementation SomeObject
@end

I can access the property from the instance using the -> syntax like below, as I would do in C++:

someObjectInstance->someString

Should I make a property for someString when all I want is for it to be accessible by the outside world? I would create a @property for someString in my interface and @synthesize it in my implementation, which would enable me to access it using the dot syntax.

Himanshu
  • 399
  • 3
  • 14
  • See my answer to the similar question [here](http://stackoverflow.com/questions/5555736/objective-c-why-do-we-declare-ivars-in-the-h-member-area-if-property-seems-to/19470096#19470096). – Holly Oct 19 '13 at 19:25

2 Answers2

3

Generally speaking, if you want to expose data, you should use properties. Making instance variables public is a bad idea in general.

  • 1
    The real question is: why is it a bad idea? – Himanshu Jan 24 '12 at 10:12
  • 2
    Because it makes future changes to your class impossible... what if you want to remove the actual ivar, and just return some other values by hand-implemented accessor methods? –  Jan 24 '12 at 10:14
  • What if, in this particular case, I am fairly certain that I wouldn't want to hand-implement the accessor methods. Would it be correct to use public ivars in this case? This is more of a general object-oriented question than an objective-c specific question. – Himanshu Jan 24 '12 at 10:18
  • 3
    In addition, making a habit out of accessing through getters and setters exclusively is good practice, because it allows the implementing class to control access (for instance, count the number of times a certain value has been accessed). – fzwo Jan 24 '12 at 10:26
0

Yes, because what you're doing when you make it a @property is directing folks using it to call the setSomeString and someString methods, in effect. Even if you're @synthesizeing them, it's better for your code quality to be using the methods, because you could change them if you need to. If you're just using the pointer reference, if you find yourself needing to intercept accesses you won't be able to.

Cyberfox
  • 1,125
  • 7
  • 13