Reputation: 12004
Sorry if this is basic, but I can't get my head around this. I have an array and would like to go through every single object in it and see if it isEqualToString:@"something". If tried this, but it will crash:
for (int i = 0; i < ([myNSMutableArray count]); i++) {
NSLog(@"i = %i", i);
if ([[myNSMutableArray objectAtIndex:i] isEqualToString:@"something"]) {
...
} else {
...
}
}
I'll get:
2011-07-14 13:38:40.983 MNs[21416:207] i = 0
2011-07-14 13:38:40.985 MNs[21416:207] -[__NSArrayM isEqualToString:]: unrecognized selector sent to instance 0x4c976f0
2011-07-14 13:38:40.987 MNs[21416:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM isEqualToString:]: unrecognized selector sent to instance 0x4c976f0'
Any help would be very much appreciated. Thanks in advance!
EDIT:
Sorry, I forgot. This is how I created the array:
NSMutableArray *myNSMutableArray = [[NSMutableArray alloc] init];
for (int x = 0; x < 30; x++) {
[myNSMutableArray addObject:@""];
[myNSMutableArray addObject:@"something"];
[myNSMutableArray addObject:@""];
}
EDIT2:
So sorry, the problem was that I tried to copy a mutable array ... so all of your answers are correct, I just need to pick one now, I guess.
Upvotes: 2
Views: 3954
Reputation: 8131
Try
if ([[[myNSMutableArray objectAtIndex:i] stringValue]
isEqualToString:@"something"])
because elements in array are of ID
type. You need to cast to NSString
!
And ensure that myNSMutableArray
is created correctly and isn't in autorelease!
Alloc
+ init
make array in manual release, instead [NSMutableArray array]
is in autorelease.
Hope this helps.
Upvotes: 1
Reputation:
Try This,
for (int i = 0; i < ([myNSMutableArray count]); i++) {
NSLog(@"i = %i", i);
NSString *stringToCheck = (NSString *)[myNSMutableArray objectAtIndex:i];
if ([stringToCheck isEqualToString:@"something"]) {
...
} else {
...
}
}
Upvotes: 6
Reputation: 2281
try like this..
NSMutableArray *myNSMutableArray=[[NSMutableArray alloc]initWithObjects:@"1",@"2",nil];
for (int i = 0; i < ([myNSMutableArray count]); i++) {
if ([[myNSMutableArray objectAtIndex:i] isEqualToString:@"1"])
{
NSLog(@"Hello 1");
} else
{
}
}
Upvotes: 0
Reputation: 577
If you have strings there, you should try casting it before trying to compare:
if ([(NSString*)[myNSMutableArray objectAtIndex:i] isEqualToString:@"something"]) {
Upvotes: 0
Reputation: 69027
From the error message you get, the problem seems lying with how you fill up your myNSMutableArray
. In fact,
[myNSMutableArray objectAtIndex:i]
returns __NSArrayM
instead of NSString
, hence the error you get.
Could you explain what kind of objects do you add to the NSArray
?
Upvotes: 2