objective c - Conditional Array... elegant way to do that -


i have array several elements must added or not depending on conditions. that:

nsmutablearray *myarray = [[nsmutablearray alloc] init]; [myarray addobject:@"aaa"]; [myarray addobject:@"bbb"];  if (flag)   [myarray addobject:@"flag"];  if (box)   [myarray addobject:@"box"];  [myarray addobject:@"xxx"];  if (x > 5)   [myarray addobject:@"smaller"];  if ([self ismenuvisible])   [myarray addobject:@"menu"];  ... etc. 

but appears confusing , complex.

i can imagine several methods create that, involve passing dictionary, array of objects , conditions, etc., appear more lame , more complex this.

how guys in more elegant way?

i leave alone. clear , easy understand.


but define category method if hate seeing if.

// not tested. @implementation nsmutablearray (ext) -(void)addobject:(nsobject*)obj when:(bool)condition {     if (condition) {         [self addobject:obj];     } } @end  ....  [myarray addobject:@"aaa"]; [myarray addobject:@"bbb"]; [myarray addobject:@"flag" when:flag]; [myarray addobject:@"box" when:box]; [myarray addobject:@"xxx"]; [myarray addobject:@"smaller" when:(x > 5)]; [myarray addobject:@"menu" when:[self ismenuvisible]]; 

this may maintenance burden in future though.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -