StuartM
StuartM

Reputation: 6823

Check through an Array for a specific object

I am trying to work out how many cells my table view should have. This is determined by results of a query which are stored in Array.

  1. When the view is loaded the array might not exist or have any values so the cells should be 0.

  2. How do I check through my array to check for a specific object. I understand I can use containsObject or equalTo...

My array would consists of objects like this:

{<GameTurn:TLED0qH44P:(null)> {\n    GameRef = \"<Game:KgguI4ig4O>\";\n    GameTurnImage = \"<PFFile: 0xb3da9d0>\";\n    GameTurnWord = tester;\n    OriginalImageCenterX = \"27.9\";\n    OriginalImageCenterY = \"29.39375\";\n    TurnCount = 1;\n    UploadedBy = \"<PFUser:UgkZDtDsVC>\";\n}

There would be multiple entries of the above. For each entry I need to check if the UploadedBy key is equal to the PFUser currentUser. If it is add one cell, and so on.

So I need to get an overall count of the items in the array where that key is equalto the current user.

Upvotes: 1

Views: 132

Answers (2)

MJN
MJN

Reputation: 10818

There are many ways you can filter an array in Objective-C. Here is one method using blocks and NSIndexSet.

You can grab all the indexes of your original array where the objects pass a test, specified in the block. Then create another array consisting of the objects at those indexes.

// get all indexes of objects passing your test
NSIndexSet *indexes = [myArray indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    // replace this with your equality logic
    return [obj uploadedBy] == [PFUser currentUser];
}];

// Filled with just objects passing your test
NSArray *passingObjects = [myArray objectsAtIndexes: indexes];

Upvotes: 2

Martin R
Martin R

Reputation: 540115

You can filter the array to get a new array of all matching objects:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"UploadedBy = %@", currentUser];
NSArray *filtered = [array filteredArrayUsingPredicate:predicate];

and use the filtered array as table view data source.

If the array comes from a Core Data fetch request, it would be more effective to add the predicate to the fetch request already.

Upvotes: 2

Related Questions