Question

When I declare an NSString I simply do:

NSString * my_string; (in interface of my .h)

If I want to allow access to this string from other classes I add a property in this way

property (nonatomic, strong) NSString *my_string;

and I write the synthesize

synthesize my_string; (in .m)

Now I have some question about:

  1. If I use a property, must I also use the simple declaration in interface?
  2. If I use my_string as a property, must I always use self. before?
  3. If I use a property, is it necessary to write @synthesize for each? (because I saw that sometimes it's not necessary.
Was it helpful?

Solution

If I use a property, must I also use the simple declaration in interface?

No, generally you just want to use the @property (it will quietly add an instance variable for you).

If I use my_string as a property, must I always use self. before?

You don't need to but you should. Using self. calls the accessor method to get the variable contents. Not using self. accesses the instance variable directly. So, if you add a custom accessor in the future you will need to refactor.

Often you will reuse the same variable multiple times. In this case, call self., but use it to set a local variable that you then use throughout the method (in this way the accessor is only called once).

If I use a property, is it necessary to write @synthesize for each? (because I saw that sometimes it's not necessary.

No, the compiler will add:

@synthesize propertyName = _propertyName;

for you, and that is a good approach to follow (separating the property name from the instance variable name).

OTHER TIPS

  1. NO
  2. NO, using self. will execute accessor method, you can use it with name _my_string and then you'll access the variable directly. If you want a different variable name for your property then you must use synthetize with that name
  3. NO, xcode will synthetize it automatically with the variable named _my_string

It's becoming more and more appropriate to use properties in all cases anymore. You can declare "private" properties inside a header extension inside the .m file if you don't want to expose them to outside classes. Say you have a property called name in the .h file:

@property (nonatomic, strong) NSString *name;

Users of this class can access the name property by saying theVariable.name, inside your .m file you need to access this property with self.name. However you can access the ivar like so:

_name = @"John Smith"

This will skip the property and go directly to the ivar. In this case if you had an overriden setter it won't be called.

You no longer need to synthesize properties. Xcode will automatically provide this:

@synthesize name = _name;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top