Laurenz Glück
Laurenz Glück

Reputation: 1762

Check if array contain specific string

I am saving different codes in a array and now want to check if one code is in the array.

I searched a bit around but nothing working...

Here you see how my array looks:

2013-04-28 12:43:23.877 myApp[9422:907] PushArray: (
    {
    code = 123;
    titel = "Test 01";
},
    {
    code = 456;
    titel = "Test 02";
},
    {
    code = 789;
    titel = "Test 03";
}
)

I tried this to check:

NSString *code = [NSString stringWithFormat:@"123"];;

if ([PushArray containsObject:code]) {
    NSLog(@"Code true!");
}else {
    NSLog(@"Code false!");
}

But every time I get "Code false!" back...

Upvotes: 0

Views: 3151

Answers (1)

Michael Dautermann
Michael Dautermann

Reputation: 89509

The objects in your array are actually NSDictionary objects. So to compare numbers, let's enumerate on the array and do the compare on the value from that dictionary object:

NSNumber * code = [NSNumber numberWithInteger: 123];
for(NSDictionary * anEntry in pushArray)
{
    NSNumber * numberFromEntry = [anEntry objectForKey: @"code"];
    if([code isEqualToNumber: numberFromEntry])
        NSLog( @"code true!");
}

Also, notice that I changed the name of your array from "PushArray" to "pushArray". Standard Objective-C convention is to use lowercase letters for variables & objects and use uppercase for naming classes.

(the original version of my answer -- which I quickly caught and edited -- was to compare the strings; but I'm guessing those code values in the dictionary objects are actually numbers and not strings)

Upvotes: 1

Related Questions