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:
my_string
as a property, must I always use self.
before?@synthesize
for each? (because I saw that sometimes it's not necessary.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).