Getting a random object from an array, then remove it from array. iphone -
i having problem arrays, want object picked randomly array, , remove , remove other objects specified in "if" statement.
what did..
in .h
nsmutablearray *squares; int s; nsstring *randomn; next, in .m
create new array:
-(void) array{ squares = [[nsmutablearray alloc] arraywithobjects: @"a", @"b", @"c", nil]; } and choose random object, if properties of "if" met, remove object array, while loop again.
-(void) start{ s=5; while (s > 0){ //i tried without next line.. randomn = nil; //also tried next line without ' % [squares count' randomn = [squares objectatindex:arc4random() % [squares count]]; if (randomn == @"a"){ [squares removeobject: @"a"]; [squares removeobject: @"b"]; s = s - 1; } if (randomn == @"b"){ [squares removeobject: @"b"]; [squares removeobject: @"c"]; s = s - 1; } if (randomn == @"c"){ [squares removeobject: @"c"]; s = s - 1; } else { s=0; } } } when run app, app stops , quits loop starts.
can please me?
their few issues tripping up:
you're initializing allocated array convenience constructor, should pick 1 of alloc/init pair or convenience constructor itself:
[[nsmutablearray alloc] initwithobjects:...] or:
[nsmutablearray arraywithobjects:...] your remove lines attempting remove string literals. while array contains string instances contain same values strings you're trying remove, they're not same exact instances of string. need use [stringvar isequaltostring:otherstringvar] compare values instead of references:
if ([randomn isequaltostring:@"a"]) instead of:
if (randomn == @"a") also, else statement fire every time similar reasons second problem. if use correct string comparisons, logic off if you're trying execute 1 of 4 blocks of code. accomplish that, each of ifs after first needs else, so:
if (/* test 1 */) { } else if (/* test 2 */) { } else if (/* test 3 */) { } else { // chained else's make 1 block able execute } instead of:
if (/* test 1 */) { } if (/* test 2 */) { } if (/* test 3 */) { } else { // else applies last if! }
Comments
Post a Comment