iphoneobjective-ciosobject-code

in the ViewController.m, what's the difference between self.username with _username


@synthesize username = _username;
//Method1
    - (void) viewDidLoad
{
self.username = @"admin";
}

//Method2
- (void) viewDidLoad
{
   _username = @"admin"
}

Both are worked, and what's the difference?
can I use _username at all? when I use self.username,it will go @synthesize username;
Is self.username a method?
_username just a variable?
I write the _username in several methods. It also can worked in the View. self.username is faster than _username or not?


Solution

  • The self.username will call the setter of the username that's why the breakpoint jumps to the synthesize statement.

    When you a _variable, then the property can be accessed using the _variable. And in your case:

    self.username stores the value to ivar _username and _username = @"admin"; is also stores the value to _username ivar. Means both saves to same ivar _username.

    Listing 4-2 Using @synthesize You can use the form property=ivar to indicate that a particular instance variable should be used for the property, for example:

    @synthesize firstName, lastName, age=yearsOld;

    This specifies that the accessor methods for firstName, lastName, and age should be synthesized and that the property age is represented by the instance variable yearsOld. Other aspects of the synthesized methods are determined by the optional attributes

    Please refer http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/chapters/ocproperties.html