ios7 - Dot vs arrow notation in Objective-C for non structs -
i've seen examples of arrow notation used structs. in 1 tutorial, saw syntax in view controller implementation file:
self->webview.cangoback) backbutton.enabled = yes;
i have no idea why did not use dot notation. no explanation given. tried in simple project has button , text field. below put in button press method:
//header file @property (strong, nonatomic) iboutlet uitextfield *myinputfield; //implementation file self.myinputfield.text = @"another test"; //self->_myinputfield.text = @"text field test";
either line of code works without issue. why use 1 of above lines on other?
also, notice arrow notation produces _myinputfield.text
. significance of underscore?
in objective-c, objects c structs. if you're new language, knowledge in more trouble help. helps explain you're seeing.
an objective-c property helpful construct creates ivar in object (a new field in class's struct) defaults property name prefixed underscore. property create getter , setter methods, e.g. - (uitextfeild *)myinputfield
, - (void)setmyinfputfield
.
dot notation objective-c syntactic sugar calls objective-c setter , getter methods. ->
arrow notation c syntax dereference object's pointer , access struct field object's ivar.
it important understand dot syntax generating calls these methods, don't try , override methods , inadvertently include calls themselves.
the default implementation of generated method - (uitextfeild *)myinputfield
looks this
- (uitextfeild *)myinputfield { return self->_myinputfield; }
but objective-c has yet syntactic helper allowing access _myinputfield
without writing out self->
. following implementation identical.
- (uitextfeild *)myinputfield { return _myinputfield; }
there reasons using direct ivar access -- biggest reasons being implementation of custom setters , getters, performance, , careful control on kvo language features. in modern objective-c should avoided unless know you're doing.
if want learn more, read apple's documentation on objective-c
Comments
Post a Comment