Programmatic Object Creation in Objective-C -
below there 2 methods programmatically alloc
, init
objects of various classes , 'types'.
- (id)buildobjectofclass:(nsstring *)classstring andtype:(nsstring *)typestring { id buildobject; class classname = nsclassfromstring(classstring); sel initwithtypeselector = nsselectorfromstring(@"initwithtype:"); if ([classname instancesrespondtoselector:initwithtypeselector] == yes) { buildobject = [[classname alloc] performselector:initwithtypeselector withobject: typestring]; } return buildobject; }
this method implementation written more tersely simply:
{ return [[classname alloc] initwithtype:typestring]; }
questions are: 1) verbose version necessary? , 2) if so, programmed best be? there shortcuts or best practices neglecting?
the difference between verbose , terse versions of method verbose version validates class instances can respond -initwithtype:
not standard nsobject
init function.
it unnecessary use verbose version if of following true:
- you using
-init
, not-initwithtype:
- you every class instantiate able handle
-initwithtype:
- you don't mind application unexpectedly quitting unknown method exception if class instantiate not respond
-initwithtype:
this version (although should set buildobject
nil handle error case explicitly) returns nil
if class isn't found or if doesn't respond -initwithtype:
. terse version returns nil
if class isn't found , throws exception if class instances don't respond -initwithtype:
.
Comments
Post a Comment