Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C constants: NSString comparison using ==?

The discussions I found about setting NSString constants made me code it the following way:

.h file:

extern NSString * const kSectionHeaders;

.m file:

NSString * const kSectionHeaders = @"header";

As the program runs, it has to test words from a text file against a series of NSString constants.

I read memory comparison should work when setting function like stated above:

if (property == kSectionHeaders) {...}

Doesn't work tough :( The following works, but it was described as a bad solution (slower, what else?):

if ([property isEqualToString:kSectionHeaders]){...}

I feel I've done something wrong. But can't see what! Please help :-) Thanks! J.

like image 676
Jem Avatar asked Jan 23 '12 22:01

Jem


3 Answers

== does pointer comparison, it won't compare the values of two objects. isEqualToString: (and in general isEqual:) is the right way to do this - where was it described as a "bad solution"?

like image 137
CRD Avatar answered Nov 02 '22 20:11

CRD


Remember variable names are just pointers to objects in memory.

The == operand compares the pointers. It will not be true unless it is comparing the exact same object in memory.

isEqualToString: is your best bet. Don't worry too much about speed. The devices are plenty fast enough to do the comparison in the blink of an eye. The things that really take noticible time are drawing on screen and reading from disk.

like image 26
jackslash Avatar answered Nov 02 '22 19:11

jackslash


Who described that as a bad solution? It is the only proper/correct solution to the problem at hand.

like image 4
Joshua Weinberg Avatar answered Nov 02 '22 20:11

Joshua Weinberg