0

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,

1
  • What is in matchArray before if statement? Commented Feb 16, 2011 at 15:00

3 Answers 3

5

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hey thanks for that. It seems to be working now, although I'm getting NSExceptions being thrown now...
@Eamorr: Where, and what do they say?
Terminating app due to uncaught exception 'NSRangeException', reason '*** -[NSArray objectAtIndex:]: index 0 beyond bounds for empty array'. Think I need to check if array has a value before doing the if statement... Thanks!
@Eamorr: Yeah, other than that it should be fine.
1

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

2 Comments

Ok, I tried if([matchArray objectAtIndex:0) xxxxx @"asdf"), but what goes where the xxxxx is? isEqualToString doesn't show in the auto-complete... Many thanks,
[[matchArray objectAtIndex:0] isEqualTo: @"asd"]
0

try to use:

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

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

3 Comments

isEqualToString doesn't come up on the auto-complete ;(
try this one, with objectAtIndex
Hey, it's working now, once I surrounded it with square brackets

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.