objective-c - 为什么 -[NSString 比较 :options:] return true when the strings are not equal?

标签 objective-c cocoa nsstring

我正在检查一个字符串是否在数组中连续出现两次。这段代码似乎不起作用,因为它只是打印出整个数组。我错过了什么?

NSString *nameString =
    [NSString stringWithContentsOfFile:@"/usr/share/dict/words"
                              encoding:NSUTF8StringEncoding
                                 error:NULL];

NSArray *names = [nameString componentsSeparatedByString:@"\n"];

//Save last item
NSMutableString *lastOne = [NSMutableString stringWithCapacity:20];

// Go through the array one string at a time
for (NSString *n in names) {

    if ([n compare:lastOne options:NSCaseInsensitiveSearch]) {
        NSLog(@"%@", n);
    }

    [lastOne setString:n];


}

最佳答案

compare:和相关函数不返回 bool 值,它们返回 NSComparisonResult 。如果您想查看字符串是否相等,您应该使用

if ([n compare:lastOne options:NSCaseInsensitiveSearch] == NSOrderedSame)

关于objective-c - 为什么 -[NSString 比较 :options:] return true when the strings are not equal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22442172/

相关文章:

ios - 如何为 iOS 应用程序使用现有的 GCM 发件人 ID

objective-c - 在代码中将 NSTreeController 绑定(bind)到 NSOutlineView

ios - 如何将 NSValue 转换为 NSString

ios - 格式字符串未使用数据参数?

ios - 使 TableView 按钮占用更少的内存

javascript - 可以将 Javascript 编写成脚本到 xcode 中吗?

ios - 委托(delegate)函数的顺序在 iOS 中重要吗?

macos - 在MAC cocoa 应用程序中显示通知编号

cocoa - 如何在 Cocoa 中为 NSView 创建 View Controller 第一响应者

iphone - ARC 禁止自动释放?