Reputation: 1331
In my application I am having entity class like:
#import <Foundation/Foundation.h>
@interface classAbc : NSObject
{
NSString *strTitle;
int iId;
}
@property(nonatomic, retain) NSString *strTitle;
@property(nonatomic) int iId;
@end
and in my NSMutableArray I am storing objects of this class like:
classAbc *objAbc=[[classAbc alloc] init];
objAbc.iId=1;
objAbc.strTitle=@"Title 1";
classAbc *objAbc1=[[classAbc alloc] init];
objAbc1.iId=2;
objAbc1.strTitle=@"Title 2";
NSMutableArray *arrTemp=[[NSMutableArray alloc] initWithObjects:objAbc,objAbc1,nil];
[objAbc release];
[objAbc1 release];
and now runtime I want to retrieve Object from this array based on objAbc.iId condition like:
if arrTemp contains object having its iId value as 2 for example.
Can any one suggest way other than for loop iteration? As number objects can increase for loop will take lot of time to find it.
Thanks in advance.
Upvotes: 1
Views: 2416
Reputation: 131
Use predicateWithBlock: to get the object of specific property. NSPredicate Link
Upvotes: 1
Reputation: 1331
After searching I got answer to this question. Using NSPredicate is the best way for such condition. Using NSPredicate we can apply condition on any member of the class object.
This is link for MAC OS X however this works on iPhone sdk with some changes. NSPredicate
Upvotes: 0
Reputation: 13713
I suggest you use NSMutableDictionary for storing your object where the key is the object's id and the value is the object itself. If you don't mind for the order use this approach.
classAbc *objAbc=[[classAbc alloc] init];
objAbc.iId=1;
objAbc.strTitle=@"Title 1";
classAbc *objAbc1=[[classAbc alloc] init];
objAbc1.iId1=2;
objAbc1.strTitle1=@"Title 2";
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:objAbc1 forKey:objAbc1.iId1];
.
.
.
classAbc *abc = (classAbc*)[dict objectForKey:[NSNumber numberWithInt:2]];
Note : change id from type int to type NSNumber so you can store it as a key
Upvotes: 1
Reputation: 119242
You could kook at filteredArrayUsingPredicate: but to be honest that's probably just doing fast enumeration in the background.
Make sure your "for loop" is actually a fast enumeration loop rather than using the count of the array as a loop integer:
for (classAbc* obj in arrTemp)
{
// check for your match
break; // if found
}
Only try something more complex if this actually gives you measurable performance problems.
Upvotes: 0