HurkNburkS
HurkNburkS

Reputation: 5510

Compare Objective-C const char with NSString

I was wondering if there is a simple way to compare a const char with an NSString, or do I have to convert the const char to an NSString before doing do?

I have been looking through Apple docs but struggling to find an answer to my question.

Upvotes: 1

Views: 12359

Answers (3)

Mark Bernstein
Mark Bernstein

Reputation: 2080

Better still:

 [str isEqualToString: @(myChar) ];

This is no worse than a cast, which you're bound to need since the types are incommensurable.

Upvotes: 4

CodaFi
CodaFi

Reputation: 43330

Either

NSString *str = @"string";
const char *myChar = "some string";
if (strcmp(myChar,  str.UTF8String))

or

[str isEqualToString:[NSString stringWithUTF8String:myChar]];

The core foundation route is also an option:

CFStringRef myStr = CFSTR("some chars");

bool result = CFStringCompareWithOptions(myStr, ((__bridge CFStringRef)str),CFRangeMake(0,CFStringGetLength(myStr)), kCFCompareCaseInsensitive);

Upvotes: 12

Sebastian
Sebastian

Reputation: 7720

You are comparing two different things, so you have to convert one to the other. Which way you convert is up to you.

Upvotes: 0

Related Questions