Friday, August 23, 2013

Nested NSArray filtering

Nested NSArray filtering

I have the need to obtain the maximum value of a property of a collection
of custom objects of the same class. The objects are stored in a NSArray,
and the property happens to be another NSArray of numbers.
Let me explain in detail:
NSArray *samples; // of CMData, 4000 elements
CMData is a class that models a sample, for a specific moment in time, of
a set of different channels that can have different values.
@interface CMData : NSObject
@property (nonatomic) NSUInteger timeStamp;
@property (nonatomic, strong) NSArray *analogChannelData; // of NSNumber,
128 elements
@end
(I have stripped other properties of the class not relevant to the question)
So for example, sample[1970] could be:
sample.timeStamp = 970800
sample.analogChannelData = <NSArray>
[
[0] = @(153.27)
[1] = @(345.35)
[2] = @(701.02)
...
[127] = @(-234.45)
]
Where each element [i] in the analogChannelData represents the value of
that specific channel i for the timeStamp 970800
Now I want to obtain the maximum value for all the 4000 samples for
channel 31. I use the following code:
NSUInteger channelIndex = 31;
NSMutableArray *values = [[NSMutableArray alloc] init]; // of NSNumber
// iterate the array of samples and for each one obtain the value for a
// specific channel and store the value in a new array
for (CMData *sample in samples) {
[values addObject:sample.analogChannelData[channelIndex]];
}
// sort the array of values
[values sortUsingSelector:@selector(compare:)];
// the maximum is the last object
NSNumber *maxValue = [values lastObject];
I want to replace this programming structure by a filter through an
NSPredcicate or use valueForKeyPath: to obtain the maximum of the data I
need.
Anyone knows how to do this without a for loop? Just using NSPredicates
and/or valueForKeyPath?
Thank you very much in advance for your help.

No comments:

Post a Comment