I am having a problem with arrays, I want an object to be picked randomly from the array,
and then remove it and remove other objects that are specified in the “if” statement.
What I did..
in the .h
NSMutableArray *squares;
int s;
NSString *randomN;
Next, in the .m
Create a new array:
-(void) array{
squares = [[NSMutableArray alloc] arrayWithObjects: @"a", @"b", @"c", nil];
}
and then choose a random object, if properties of the “if” met, remove the object from the array, do the while loop again.
-(void) start{
s=5;
while (s > 0){
//I even tried it without the next line..
randomN = nil;
//Also tried the 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 I run the app, the app stops and quits as soon as the loop starts.
Can you please help me?
Their are a few issues that are probably tripping you up:
You’re initializing an already allocated array with a convenience constructor, you should pick one of the
alloc/initpair or the convenience constructor by itself:or:
Your remove lines are attempting to remove string literals. While your array contains string instances that contain the same values as the strings you’re trying to remove, they’re not the same exact instances of the string. You need to use
[stringVar isEqualToString:otherStringVar]to compare the values instead of their references:instead of:
Also, your
elsestatement will fire every time for similar reasons as the second problem. Even if you use the correct string comparisons, your logic is probably off if you’re trying to only execute one of those 4 blocks of code. To accomplish that, each of theifs after the first needs anelse, like so:instead of: