@interface someClass : UIViewController
{
NSString *name;
}
@property (nonatomic, copy) NSString *name;
@end
Doing this you will explicitly declare both a property and an ivar.
A property is just a set of methods:
- (void)setName:(NSString*)name;
- (NSString*)name;
An ivar is the memory store holding the value that the property methods manage. This allows you to do:
self.name = ... // access through setter method
name = ... // direct access
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: strong
and weak
ownerships.
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).
@interface someClass : UIViewController
{
}
@property (nonatomic, copy) NSString *name;
@end
Here you only declare the properties; the ivar is "inferred" by the @synthesize
directive 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 @synthesize
directive, 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.
@interface someClass : UIViewController
{
NSString *name;
}
@end
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.