Difference in accessing methods


whats the difference the two?

@property (weak, nonatomic) IBOutlet UITextField *txtUsername;

NSString *userName = [self.txtUsername text];
NSString *userName = [_txtUsername text];
NSString *userName = self.txtUsername.text;
NSString *userName = _txtUsername.text;


That compare first about Self and non-Self, It doesn’t matter which one you use, it just a syntax. But I suggest put Self because it will let people understand the object or the method is define in current class especially when you have Class method mix within.


And about the self.txtUsername and _txtUsername.
please notice the keyword @property. This means Xcode will done the setter and getter for you, it all about encapsulate.
see this Here


self.txtUsername is a getter/setter shortcut and safe for concurrency programming/multi-threaded.
_txtUsername is accessing the variable representing self.txtUsername that was created by the compiler for you where it stores the value and it is a direct access not safe in concurrency situations.

@property (weak, nonatomic) IBOutlet UITextField *txtUsername;

creates _txtUsername automatically with a setter and getter method like so:

  • (void)set TxtUsername:(NSString*)aTxtUsername{
    _txtUsername = aTxtUsername;

  • (NSString*) txtUsername {
    return _txtUsername;

You can use either if it is accessed or modified in one thread only and your example is a UIKit object then must be on the main thread only.


@5SMNOOSNM5 and @nmariano

Im just wondering is there a recommended use for each case?


Declare objects with @property, use _txtUsername only Inside setter and getter otherwise [self.txtUsername text].


Thank you for the guidance.