【问题标题】:Obj-C, function to return index of nsstring found in nsarray?Obj-C,返回nsarray中找到的nsstring索引的函数?
【发布时间】:2011-09-18 17:03:11
【问题描述】:

我一直在寻找是否可以找到像 indexOf 这样的函数。

我有一个数组。

self.data = [[NSArray alloc] initWithObjects:@"apple", @"lemon", @"pear", nil];

寻找一个返回的函数,它会寻找柠檬并返回 1 ?

【问题讨论】:

    标签: objective-c cocoa-touch nsstring nsarray


    【解决方案1】:

    indexOfObject: 怎么样?

    NSUInteger index = [self.data indexOfObject:@"lemon"];
    

    【讨论】:

    • 这行不通。由于字符串是指向对象的指针,因此您无法比较它们是否相等。
    • indexOfObject: 使用isEqual: 来检查是否相等。这对 NSStrings 非常有效。
    【解决方案2】:

    试试这个方法。

    -(int)indexOfString:(NSString *)string inArray:(NSArray *)array {
        for(int i=0; i<[array count]; i++) {
            if ([[array objectAtIndex:i] class] == [NSString class]) {
                if ([[array objectAtIndex:i] isEqualToString:string]) {
                    return i;
                }
            }
        }
    }
    

    编辑:使用-indexOfObject: 的另一个答案更好。

    【讨论】:

      猜你喜欢
      • 2013-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多