Objective-C constants: NSString comparison using ==?

夙愿已清 提交于 2019-12-01 05:32:18

问题


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.


回答1:


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.




回答2:


== 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"?




回答3:


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



来源:https://stackoverflow.com/questions/8979408/objective-c-constants-nsstring-comparison-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!