ios - Difference between _ and self. in Objective-C -


is there difference between using underscore , using self keyword in objective-c when calling @property?

property declaration:

@property (weak, nonatomic) nsstring *mystring; 

calling @synthesize on property:

@synthesize mystring = _mystring; 

is there difference if want use in code? when? in getter/setter?

self.mystring = @"test"; _mystring = @"test"; 

self.mystring = @"test"; equivalent writing [self setmystring:@"test"];. both of these calling method.

you have written method yourself. might this:

- (void)setmystring:(nsstring*)newstring {     _mystring = newstring; } 

because used @synthesize, don't have bother writing method, can allow compiler write you.

so, looking @ method, looks calling exact same thing assigning value instance variable, right? well, it's not simple.

firstly, write own setter method. if so, method called, , sorts of additional things setting variable. in case, using self.mystring = call method, doing _mystring = not, , different functionality used.

secondly, if ever use key value observing, compiler clever tricks. behind scenes, subclasses class, , overrides setter method (whether it's 1 wrote or 1 generated synthesize), in order make calls willchangevalueforkey: needed key value observing work. don't need know how works (although it's quite interesting if want bedtime reading!), need know if want key value observing work automatically, have use setter methods.

thirdly, calling setter method if you're relying on synthesize write 1 gives flexibility future. might want whenever value changed, , @ point discover want that, can manually write setter method — if you're in habit of using self.mystring =, won't need change rest of code start calling new method!

fourthly, same applies subclasses. if else subclass code, if use setters override them adjust functionality.

any time access instance variable directly, you're explicitly not providing way functionality hooked in @ point. since or else might want hook in such functionality in future, pays use setters time, unless there's reason not to.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -