objective c - May I declare the *shape outside the for loop? -
nsmutablearray *shapes = [[nsmutablearray alloc] init]; (nsdictionary *object in array) { nsstring *type = [object objectforkey:@"type"]; shapefactory *shape = [[[shapefactory alloc] init] shapewithtype:type dictionary:object]; [shapes addobject:shape]; } self.shapes = shapes;
i want know if can declare variable *shape outside loop , still work
first of: yes, roee84 said, valid syntax , can that. however, fact have (deducing method name) factory class pattern here , type of created shape seems defined special argument, wonder why you're using shapefactory
. why not use id
? array won't care object , it's better not pretend objects of same type factory class object.
that being said, code correct. of course, can also declare shape
(the *
considered part of type, btw) outside of loop. don't need declare local mutable array (assuming property mutable array). i'll use id
in example illustrate said above:
self.shapes = [[nsmutablearray alloc] init]; id shape; // declaration! note no * id nsobject * (nsdictionary *object in array) { nsstring *type = [object objectforkey:@"type"]; shape = [[[shapefactory alloc] init] shapewithtype:type dictionary:object]; [self.shapes addobject:shape]; }
if property not mutable array, can't self.shapes = [[nsmutablearray alloc] init]
, etc., of course, i'd suggest being safe last line , write self.shapes = [nsarray arraywitharray:shapes]
. may seem bit paranoid, way you're not casting mutable object immutable one, have immutable 1 (i'm writing libraries , have expect users trying be... frisky stuff... ^^). can't mutated behind back.
Comments
Post a Comment