JRG-Developer
JRG-Developer

Reputation: 12663

Can I use NSPredicate for this?

Here's my loop:

- (NSArray *)myArray
{
    if (!_myArray)
    {
        NSMutableArray *array = [NSMutableArray array];

        for (MyReport *report in self.helper.myReportType.reports)
        {
            [array addObject:report.nameString];
        }        
        _myArray = array;
    }

    return _myArray;
}

This works (with obviously some casting happening, which may not be great or desirable), but surely there's a better way to do this. Can NSPredicate help here? (I'm still new to using NSPredicate, but I believe it's primarily for filtering data, not building an array like this?) Otherwise, how can I rewrite this using another Apple helper class?

Upvotes: 0

Views: 53

Answers (2)

MaxGabriel
MaxGabriel

Reputation: 7707

NSPredicate is more about filtering data, like you said. A clean way to do this is with Key-Value Coding, which when used on NSArray, calls the valueForKey: method on each of its objects, and returns the results as an NSArray:

_myArray = [self.helper.myReportType.reports valueForKey:@"nameString"];

Note that this method converts nil to NSNull automatically. More advanced KVC-Collection operator information can be found here: http://nshipster.com/kvc-collection-operators/

Upvotes: 2

Rahul Wakade
Rahul Wakade

Reputation: 4805

Use below code-

[self.helper.myReportType.reports valueForKey:@"nameString"];

It will return you array of nameString's from reports array.

Upvotes: 1

Related Questions