使用内联块在NSArray中搜索对象索引

Æle*_*lex 8 css objective-c nsarray objective-c-blocks

我已经看到了一些使用NSArray indexOfObjectPassingTest的例子,但我无法使它们工作(它们不会返回有效的索引).所以现在我正在尝试使用内联块.我通过typedef一个块,然后将其设置为属性,合成它,并在构造函数中初始化它来完成它.然而,这种方式使整个点变得无声,因为我可以轻松地创建一个方法并使用它(减少打字,减少工作量).

我想要实现的是这样的事情:

Observations *obs = [self.myAppointment.OBSERVATIONS objectAtIndex: ^NSInteger (NSString *keyword){ 
    for (Observations *obs in self.myAppointment.OBSERVATIONS) {
        if ([obs.TIME isEqualToString:keyword] == YES) return (NSInteger)[self.myAppointment.OBSERVATIONS indexOfObject:obs];
    }
    return (NSInteger)-1;
}];
Run Code Online (Sandbox Code Playgroud)

然而,Xcode根本就没有它.我尝试过不同的变体,但是内联声明它似乎是一个问题,这很奇怪,因为正如我所说的那样,键入它,声明和合成它的工作原理如下:

Observations *obs = [self.myAppointment.OBSERVATIONS objectAtIndex:findObs(keyword)];
Run Code Online (Sandbox Code Playgroud)

findObs再次是一个定义的块,它做同样的事情.这是一个语法问题,还是我错过了其他更重要的东西?

一二三*_*一二三 29

-objectAtIndex:将a NSUInteger作为参数,但是你将它传递给一个块(用表示^).您的第二个示例使用参数调用findObs(可能是您的块),将该keyword调用的结果传递给-objectAtIndex:.

你可能想结合-objectAtIndex:使用-indexOfObjectPassingTest::

NSString *keyword = /* whatever */;
NSArray *array = self.myAppointment.OBSERVATIONS;
NSUInteger idx = [array indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop){ 
    Observations *obs = (Observations*)obj;
    return [obs.TIME  isEqualToString:keyword];
}];
if (idx != NSNotFound)
    Observations *obs = [array objectAtIndex:idx];
Run Code Online (Sandbox Code Playgroud)

  • @TristanLeblanc该示例返回第一个对象--- [`indexOfObjectPassingTest:`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/#//apple_ref/occ/instm/NSArray/indexOfObjectPassingTest :)当`*stop`设置为'YES`时***停止迭代***或***谓词返回`YES`.此外,`objectAtIndex:`是一个O(1)操作,不会遍历数组. (2认同)

Moo*_*ose 6

这是一个返回字符串数组中字符串索引的示例.它可以适用于任何类型的物体.

NSString* myString = @"stringToFind";
NSUInteger objectIndex = [myStringArray indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return (*stop = ([obj isEqualToString:myString]));
    }];
Run Code Online (Sandbox Code Playgroud)

准确地回答原始问题:

NSString *keyword = @"myKeyword";
NSUInteger index = [self.myAppointment.OBSERVATIONS indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) { 
    return (*stop = [(Observations*)obs.TIME  isEqualToString:keyword]);
}];
Observations *obs = (index!=NSNotFound) ? self.myAppointment.OBSERVATIONS[index] : NULL;
Run Code Online (Sandbox Code Playgroud)

但是,这是相当奇怪的东西比较调用时与关键字... ;)