使用NSArray时避免“超出界限”的完美方法是什么

时间:2013-12-13 04:39:01

标签: ios iphone objective-c arrays

我知道一些避免这种情况的方法,例如

if (index >= [_data count] || index < 0) return nil;
    return [_data objectAtIndex:index];

但我应该离开吗?或者有关于这个主题的其他解决方案吗?

3 个答案:

答案 0 :(得分:3)

首先,我想回应一下@ rmaddy的评论,该评论就是:

  

没有通用的解决方案。每个案例都不同。

也就是说,您可以使用其他技术:

firstObjectlastObject

这些方法将返回对象,如果没有,则返回nil。这些方法永远不会抛出异常。

快速枚举

您可以使用快速枚举,永远不需要检查索引:

NSArray *myStrings = @[@"one", @"two"];

for (NSString *thisString in myStrings) {
     NSLog(@"A string: %@", thisString);
}

安全类别

如果您经常这样做,可以在NSArray上添加类别:

- (id)safeObjectAtIndex:(NSUInteger)index {
    if (index >= [self count] || index < 0) return nil;
    return [self objectAtIndex:index];
}

如果您不熟悉类别,请参阅Customizing Existing Classes

这样做的一个缺点是在代码中找到错误可能更难。

答案 1 :(得分:0)

在苹果库中NSArray objectAtIndex方法:

objectAtIndex:
Returns the object located at the specified index.

- (id)objectAtIndex:(NSUInteger)index
Parameters
index
An index within the bounds of the array.
Return Value
The object located at index.

您可以使用“NSUInteger index;”所以“if(index&lt; 0)”可以省略。

在我看来,如果你需要为其他人提供一些界面,你可能需要添加这些代码以避免“超出界限”。 但是如果你的代码只适合你自己,你就不需要做这些事情,因为大多数时候你需要的是数组中的一个对象而不是nil。如果索引超出限制,则必须存在一些需要修复的逻辑错误。让异常去找你的错误。

答案 2 :(得分:0)

你可以在调用objectAtIndex之前调用objectAtIndex方法,调用'custom_objectAtIndex'之类的方法来检查是否超出范围。

+ (void)load{
    Method method1 = class_getInstanceMethod(objc_getClass("__NSArrayI"),@selector(objectAtIndex:));
    Method method2 = class_getInstanceMethod(objc_getClass("__NSArrayI"),@selector(custom_objectAtIndex:));
    method_exchangeImplementations(method1, method2); 
}


- (id)custom_objectAtIndex:(NSUInteger)index{
    NSLog(@"~~~~~~~:%ld",count);
    if (index >= self.count) {
        return @"out of bounds";
    } else {
       return [self custom_objectAtIndex:index];
    }
}