比较可可中的字符串 [英] Comparing Strings in Cocoa

查看:81
本文介绍了比较可可中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过:

- (NSString*) generateString
{
    NSString* stringToReturn = @"thisString";
    return stringToReturn;
}

- (void) otherMethod
{
    NSString *returnedString = [self generateString];
    if (returnedString == @"thisString")
    { // Do this }
    else if (returnedString == @"thatString")
    { // Do that }
}

从不匹配。

我之后尝试过

if ([returnedString compare:@"thisString"] == 1)

但是比较方法总是返回1,即使与不同的字符串进行比较。

But the compare method always returns 1 for me, even when comparing with a different string.

这是正确的方法,我应该得到什么结果?

What is the correct way to do this, and what result should I expect?

推荐答案

all,你使用 == 运算符来比较两个对象指针(类型 NSString * )。所以当指针相同时返回true,而不是当字符串具有相同的内容时。如果你想比较两个字符串是否相同,你应该使用 isEqualToString: isEqual: isEqual:是更通用的,因为它适用于所有类型的对象)。

First of all, you are using the == operator to compare two object pointers (of type NSString *). So that returns true when the pointers are the same, not when the strings have the same contents. If you wanted to compare whether two strings are the same, you should use isEqualToString: or isEqual: (isEqual: is more general as it works for all types of objects).

其次, 当它们相同时返回 0 > 1 NSOrderedDescending ),当第一个大于第二个时。因此,事实上,当它们不同时(特别是当第一个大于第二个时),它只返回1 。

Second, compare: returns 0 (NSOrderSame) when they are the same, and 1 (NSOrderedDescending) when the first is greater than the second. So in fact it returns 1 only when they are different (specifically, when the first is greater than the second).

这篇关于比较可可中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆