문제

When using collection operators (e.g. @min,@max) on NSArrays using Key-Value Coding I get an exception if one of the values in the array is NSNull null.

I have to remove all NSNull null occurrences before using valueForKeyPath to make it work:

NSMutableArray *array = otherArray.mutableCopy;
[array removeObjectIdenticalTo:[NSNull null]];
NSNumber *minValue = [array valueForKeyPath:@"@min.self"];
NSNumber *maxValue = [array valueForKeyPath:@"@max.self"];

However, according to Apple's Documentation my code should work without removing NSNull null:

If the value of the right side of the key path is nil, it is ignored.

How can I use the keyPath statements to get the minimum and maximum values of the array without getting an runtime exception and without having to remove NSNull nullbefore?

도움이 되었습니까?

해결책

You misunderstood the documentation. This:

If the value of the right side of the key path is nil, it is ignored.

Means that if @min.field is nil, it will be ignored. But what you're doing is trying to calculate the minimum and the maximum of a collection containing NSNumber's. So probably the decimalValue method will be used, but NSNull is not key value compliant for that key. So you should keep removing NSNull objects from the collection.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top