NSArray 创建一个子数组,然后对值求和

NSArray creating a subarray and then summing the values

我有一些代码最初写成:

+(double)averageOfArray:(NSArray*)array fromIndex:(int)from toIndex:(int)to{
    if (to < 0) return 0;
    if (to > array.count) return 0;
    double sum = 0.0;
    for (long i = from; i < to; i++){
        sum += [array[i] doubleValue];
    }
    return sum/(double)(to-from);
}

但我正在尝试编写它以使其更有效率。我不知道这是否会更快,但一个想法是创建一个子数组,然后像这样调用 valueForKeyPath:@"sum.self"

...
NSArray *t = [array subarrayWithRange:NSMakeRange(from, to-from)];
double sum = [[t valueForKeyPath:@"sum.self"] doubleValue];
return sum/(double)(to-from);

但是这是抛出一个错误:

Thread 1: Exception: "[<__NSCFNumber 0xd99f8c3636814118> valueForUndefinedKey:]: this class is not key value coding-compliant for the key sum."

查看调试器,它显示我的 NSArray *tt = (__NSArrayl_Transfer *) @"500 elements"。但是,当我查看像这样 NSArray *testArray = @[@0.1, @0.2, @0.3, @0.4 @0.5, @0.6]; 创建的数组时,它显示为 testArray = (__NSArrayl *) @"6 elements"。我假设由于某种原因这些底层类型是问题所在。

我已经尝试通过这样做来创建一个新数组:

NSArray *t = [[NSArray alloc] initWithArray:[array subarrayWithRange:NSMakeRange(from, to-from)] copyItems:YES];`

但这并不能解决问题。我有什么不明白的?

Using Collection Operators:

When a key path contains a collection operator, any portion of the key path preceding the operator, known as the left key path, indicates the collection on which to operate relative to the receiver of the message. If you send the message directly to a collection object, such as an NSArray instance, the left key path may be omitted.

The portion of the key path after the operator, known as the right key path, specifies the property within the collection that the operator should work on. All the collection operators except @count require a right key path.

Operator key path format

keypathToCollection.@collectionOperator.keypathToProperty
|_________________| |_________________| |_______________|

   Left key path         Operator        Right key path
  • 您将消息直接发送到集合对象,您可以省略左键路径。
  • 集合运算符总是以 @ 开头。
  • 需要右键路径(@count除外)。

因为忘记使用@前缀,以下代码...

double sum = [[t valueForKeyPath:@"sum.self"] doubleValue];

... 尝试从数组中的每个 NSNumber * 中获取 sum。然后你得到:

Thread 1: Exception: "[<__NSCFNumber 0xd99f8c3636814118> valueForUndefinedKey:]: this class is not key value coding-compliant for the key sum."

只需在集合运算符中添加 @ 前缀即可:

double sum = [[t valueForKeyPath:@"@sum.self"] doubleValue];