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

StackOverflow https://stackoverflow.com/questions/13600636

Pregunta

@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?

¿Fue útil?

Solución

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

Otros consejos

I would suggest you to go through the apple documentation - Declared Properties. self.username is equivalent to the getter and setter methods in other languages. Just a few things about this. Before ARC, it used to help in ensuring following the memory management part as well(Handling retain, release, copy of params). _username is mostly used in methods such as init when it is not recommended to use self.param in init and dealloc.

Difference between self.username with _username.

self.username uses accessors (setter and getters). They call the method and in the method the ivar is accessed.

_username uses the ivar directly. NO method call, so this may save a bit of overhead.

self.username makes your class KVO compliant, while _username bypasses it.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top