I'm some what confused as to the difference between accessing an instance variable via self or just by name (when working inside the class).
For instance, take this class:
.h:
@interface Register : NSObject {
NSString *mName;
}
- (id) initWithName:(NSString *) name;
.m:
- (id) initWithName:(NSString *)name
{
if (self == [super init])
{
mName = name;
}
return self;
}
What's the difference between accessing the instance variable via
self.mName = name;
vs
mName = name;
Which isn't a @property and is not @sythenize'd.
Say it is this though, per this example:
.h:
@interface Manange_My_ViewsViewController : UIViewController {
IBOutlet UILabel *countLabel;
}
@property (nonatomic, retain) IBOutlet UILabel *countLabel;
.m:
@synthesize countLabel;
- (void) updateLabel:(NSUInteger)count
{
countLabel.text = [NSString stringWithFormat:@"%d", count];
}
But say I accessed countLabel as:
self.countLabel
What would be the difference?
Edit: Third example per users' answer: Say it the iVar wasn't an IBOutlet:
.h:
@interface Fake : NSObject {
NSString *mVar;
}
@property (nonatomic, retain) NSString *mVar;
.m:
@synthesize mVar;
mVar = @"";
VS
self.mVar = @"";
Or is it the same - that in the first we are accessing the actual instance variable and in the second we're actually going through the auto created setter (via @synthesize)?
Thanks all!
Edit: Update in response to Peter Hosey ...
So your thinking the convention of mVarName is bad? I took that from my C++ days.
But what about the case when you do?
-(void) someMethod:(int) x
{
x = x;
}
You can't do that (Say 'x' is also a class variable)
But you can do:
-(void) someMethod:(int) x
{
mX = x;
}
But your saying its better to do:
-(void) someMethod:(int) x
{
self.x = x;
}