Gopinath
Gopinath

Reputation: 5442

How to find a particular object from an NSMutableArray iPhone app?

I have store many values in NSMutableArray like @"New", @"Old", @"Future". The NSMutablArray having 100+ objects. I need to find the @"New" objects from the array. Can anyone please help me to solve this issue? Thanks in advance.

Upvotes: 3

Views: 18069

Answers (4)

Mundi
Mundi

Reputation: 80273

This will do the trick most economically [tested]:

[myArray filteredArrayUsingPredicate:[NSPredicate
   predicateWithFormat:@"self == %@", @"New"]];

Upvotes: 13

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39988

Gopinath if you have added constant string like @"New" then

int index = [array indexOfObject:@"New"];

will do the trick as

NSString *str1 = @"New";
NSString *str2 = @"New";

Then str1 and str2 points to same object.
And if you know the string that you are searching then is there any need of finding it?
Mundi's answer is also good.

Upvotes: 3

marcus.ramsden
marcus.ramsden

Reputation: 2633

Why not just do a fast enumeration of the objects?

NSMutableArray *matchingObjects = [NSMutableArray array];
NSArray *objects = [NSArray arrayWithObjects:@"New", @"Old", @"Future", nil];
NSInteger count = 0;
for (NSString *string in objects) {
    if ([string isEqualToString:@"New"]) {
        [matchingObjects addObject:string];
    }
    count++;
}

This way matchingObjects contains all of the objects that matched the test, and you can use count to get the index of all the matches.

Upvotes: 1

J2theC
J2theC

Reputation: 4452

I would suggest to filter the array using a predicate block

[array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary * bindings){
    [evaluatedObject isEqual:anObject];
}]];

Upvotes: 0

Related Questions