I have got a header file (.h) and I want to declare name but all these ways work the same I think because I haven’t seen any difference with functionality. Could you tell me what the difference is between:
This with both declarations:
@interface someClass : UIViewController
{
NSString *name;
}
@property (nonatomic, copy) NSString *name;
@end
Without variable:
@interface someClass : UIViewController
{
}
@property (nonatomic, copy) NSString *name;
@end
Or Without property:
@interface someClass : UIViewController
{
NSString *name;
}
@end
Doing this you will explicitly declare both a property and an ivar.
A property is just a set of methods:
An ivar is the memory store holding the value that the property methods manage. This allows you to do:
The advantage of using properties is that they deal with memory management for you. E.g., in your case, the property is of type
copy: this means that with the first syntax (self.name = ...) a copy of the object will be done. If not using properties, you would explicitly need to do:name = [originalString copy];to obtain the same effect.Other options you can specify for properties (but not ivars) are:
strongandweakownerships.Furthermore, a property also represents a public interface to access the variable from outside your class.
Using direct access you are on your own as to memory management (if you are not using ARC).
If you are using ARC and don’t define properties, you will not be able to control how the memory is managed by specifying the ownership: strong, weak, retain).
Here you only declare the properties; the ivar is "inferred" by the
@synthesizedirective in your implementation file. This is only possible in Objective C 2.0 and later (previously, the ivar declaration as above was mandatory).The same considerations as above applies, with a minor nuance: with older versions of LLVM (ObjC compiler) you will not be able to reference directly the auto-synthesized ivar; with current version of LLVM, if you omit the
@synthesizedirective, then an automatic ivar named after your property would also be declared (in your case it would be_name).This last paragraph may seem a bit "advanced", or contrived, but you can safely ignore it.
In this case you are only declaring the ivar. No accessor methods. You will need to handle memory management on your own (if not using ARC), futhermore you will not be able to access the variable from outside the class. For that you need accessors.
Hope this helps.