是 - [NSOrderedSet indexesOfObjectsPassingTest:]真的返回NSIndexSet或NSNotFound吗?

时间:2013-06-13 17:56:52

标签: objective-c cocoa-touch nsorderedset

我有这段代码:

NSIndexSet *indexes = [anOrderedSet indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        if([self testObj: obj]) return YES;
        else return NO;
    }];

    if(indexes == NSNotFound) NSLog(@"No objects were found passing the test");

这导致Xcode发出警告,指出“指针和整数之间的比较('NSIndexSet *'和'int')”。我完全同意Xcode的这一点。

但是,函数的返回值是NSIndexSet*类型,Apple文档(http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSOrderedSet_Class/Reference/Reference.html)表示:

  

返回值
  通过谓词指定的测试的有序集中对应值的索引。如果有序集中没有对象通过测试,则返回NSNotFound ..“

那么当函数的返回类型是指向NSNotFound的指针时,返回NSIntegerNSIndexSet)的处理是什么?通过将比较更改为:

来抑制警告是否安全
if(indexes == (NSIndexSet*) NSNotFound) NSLog(@"No objects were found passing the test");

因为从理论上讲,索引可能是一个有效的返回NSIndexSet指针,恰好指向一个等于NSNotFound的内存地址,对吗?

2 个答案:

答案 0 :(得分:6)

我担心文档错误。

您应该检查空的NSIndexSet

if ([indexes count] == 0) NSLog(@"No object were found passing the test");

您可能应该向Apple打开错误报告。

答案 1 :(得分:1)

显然Apple文档不正确。

在我的测试中,我发现如果有序集中没有对象通过测试,则返回的对象是计数等于零的NSIndexSet。

因此,正确的测试是:

if(indexes.count == 0) NSLog(@"No objects were found passing the test");