Eamorr
Eamorr

Reputation: 10012

Objective C: Compare Array Element to String

Greetings,

I'm trying to simply compare a NSString to an NSArray.

Here is my code:

NSString *username=uname.text;
    NSString *regex=@"^[a-zA-Z0-9-_.]{3,20}$";
    NSArray *matchArray=nil;
    matchArray=[username componentsMatchedByRegex:regex];
    if(matchArray[0] == "asdf"){   //this line causes the problem!
        NSLog(@"matchArray %@",matchArray);
    }

I get an "invalid operands to binary ==" error.

How can I compare the string?

Many thanks in advance,

Upvotes: 0

Views: 5131

Answers (3)

BoltClock
BoltClock

Reputation: 723568

You are trying to compare an NSString to a C string (char *), which is wrong. matchArray is an NSArray so you cannot treat it as a C array either, you have to use its objectAtIndex: method and pass in the index.

Use this instead:

if ([[matchArray objectAtIndex:0] isEqualToString:@"asdf"]) {
    NSLog(@"matchArray %@", matchArray);
}

Addressing your comments, the reason why isEqualToString: does not show up in autocomplete is because Xcode cannot guess that matchArray contains NSStrings (it only knows it contains ids, that is, arbitrary Objective-C objects). If you really wanted to be sure, you can perform an explicit cast, but it doesn't matter if you don't:

if ([(NSString *)[matchArray objectAtIndex:0] isEqualToString:@"asdf"]) {
    NSLog(@"matchArray %@", matchArray);
}

Upvotes: 5

griotspeak
griotspeak

Reputation: 13247

you want to use -objectAtIndex to get the array element. NOT the C array accessor syntax

Upvotes: 1

Matteo Alessani
Matteo Alessani

Reputation: 10412

try to use:

[[matchArray objectAtIndex:0] isEqualToString:@"asdf"];

anyway the string "asdf" should be @"asdf"

Upvotes: 0

Related Questions