Reputation: 71
The first way.
//Myclass.m
@implementation Myclass{
NSString * name;
}
-(void) print{
NSLog(@"%@",name);
}
@end
The second way.
//Myclass.m
@interface Myclass()
@property(nonatomic) NSString *name;
@end
@implementation Myclass
-(void) print{
NSLog(@"%@",_name);
}
@end
Why can't to access 'name' by 'self.name' in the first way but can use 'self.name' and '_name' in the second way. What is different between the two ways.
I confused by this because i want override the 'isEqual' method , the first way can't access the other object's private member variable but the second way can use '.' to access.
Forgive my English.
Upvotes: 0
Views: 36
Reputation: 732
When compiler will see a @property it will generate a setter and a getter (depending on annotations added to the property). So in the first example compiler adds two methods:
- (void)setName:(NSString *)name {
...
}
- (NSString *)name {
...
}
So you can call a method called 'name' in the first example because it exists ;) In the second case you would have to write them your self. Because this kind of methods are so boiler plate the @property syntax was added so the programer would not have to write basically the same code for any other variable he/she want's to use :)
Upvotes: 1
Reputation: 77641
I would use neither of these. I'd always just use the property...
//Myclass.m
@interface Myclass()
@property(nonatomic) NSString *name;
@end
@implementation Myclass
-(void) print{
NSLog(@"%@",_name);
NSLog(@"%@",self.name);
}
@end
Properties are synthesised into iVars with getter and setter methods. The iVar is always called _propertyName.
Using a property allows you to fine tune the ARC properties of that more easily than with iVars (IMO anyway).
Upvotes: 1