Difference in accessing methods


#1

whats the difference the two?

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

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


#2

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.


#3

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


#4

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.

Writing
@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.


#5

@5SMNOOSNM5 and @nmariano

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


#6

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


#7

Thank you for the guidance.