i learning ios programming, please bear me. imagine have class in want have simple init method (no params) , initialization of instance variables want done via properties. example:
@interface myclass : nsobject { } @property (nonatomic) someclass1 *p1; @property (nonatomic) someclass2 *p2; @property (nonatomic) someclass3 *p3; as mentioned have simple init, no parameters. nothing, don't implement it, inherited nsobject. so, now, if wants initialize p1,p2,p3 variables of myclass object, can't there such problematic situations, when sets:
1. myclass *object = [[myclass alloc] init]; 2. [[object p1] dosomething]; where 2nd line raise exception, because there no example object.p1 = [[someclass1 alloc] init] call before it?
it won't raise exception, because in objective-c method call on nil object pointer no-op -- nothing happens. different c++ calling instance method on null pointer cause crash.
this turns out pretty useful, because means can chain method calls without having worry intermediate method returns nil. this:
[[[[object p1] dosomething] dosomethingelse] doanotherthing]; if messaging nil object crashed or raised exception, have check result of each of 4 method calls in order safe.
for it's worth, in general, if object needs valid value p1 in order work correctly or useful, makes sense make object parameter -init method.
Comments
Post a Comment