Objective-c pointers magic. Type protection -
i have dictionary. extract 1 of values follows:
nsstring *magicvalue= [filterdict valueforkey:[filterdict allkeys][0]]; [someclass foo: magicvalue];
and foo is:
- (void)foo:(nsstring*)magicvalue { nslog("magicvalue string:%@",[magic iskindofclass:[nsstring class]] ? @"yes" : @"no"); nslog("magicvalue number:%@",[magic iskindofclass:[nsnumber class]] ? @"yes" : @"no"); }
if dictionary value number magicvalue nsnumber
. defined string pointer pointing nsnumber
. log return yes number check.
i never added protection such methods, check class "magicvalue" is. assumed when define method string parameter string.
should start accounting such behavior , add checks, or fault of guy assigned dictionary value magic in such way , used method. need best practices advice , how handle this.
this question have been answered didn't know how search it.
short answer: no, not check that, if there no special reason.
long answer:
you have differentiate between 2 cases:
a. using id
you have variable or return vale of type id
. in example -valueforkey:
. reason typing keep method generic. theoretically possible, in practice type mismatch in such situation rare , detected fast in development. different motivation asked audience (>200) in public talk, how many times had such typing error in production. listeners, of apps in of app's versions there 1(in words: one!) case. forget risk. anxiety of developers using statically typing languages (java, c++, swift).
b. wrong assignment
if not have id
type, still possible such tricks. (and want that. strength of dynamic typing.) there 2 subcategories:
you can implicitly:
nsstring *string = [nsnumber numberwithint:1];
the compiler warn that. fine, because developer see mistake. not have protect him or code.
one can explicitly:
nsstring *string = (nsstring*)[nsnumber numberwithint:1];
in such case, code can break. did explicitly. if wrong, developer had criminal energy , not have protect him himself.
Comments
Post a Comment