I have an object from a NSObject class that I call "brand" and has the following properties:
.name
.number
.site
at a given time, dozens of these objects are stored on a NSMutableArray, something like:
object 1
object 2
object 3
object 4
...
I would like to be able to retrieve a given object from the array by its number. Not the index of the object on the array but the number property of the object (get object that has the number property equal to 10, for example).
I know that NSArrays have smart methods for retrieving stuff but I don't know them deeply cause I use this rarely. Is there any way to retrieve that object from the array without having to iterate thru all objects on the array and check each object's number property?
Can you guys help? thanks.
I would recommend NSPredicate
. You could do it with something like this, assuming listOfItems
is your array containing your NSObject
's with said properties.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"number == 10"];
NSArray *filtered = [listOfItems filteredArrayUsingPredicate:predicate];
Your filtered results, any numbers matching 10
will now be in the filtered
array. If you want to cast back to your object, you can do something like this:
YourObject *object = (YourObject*)[filtered objectAtIndex:0];
Hope this helps.
NSUInteger indexOfObject10 = [myArray indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
MyObject *object = (MyObject *)obj;
return [object.number == 10];
}];
MyObject *object10 = myArray[indexOfObject10];
I prefer using block extensions to NSArray that let you "talk" to them more naturally and write less code. Something in the lines of the Smalltalk Collections jargon:
In your case I would use:
MyObject* theObject = [myArray detect:^(MyObject* each){
return each.number == 10;
}];
Here you have a possible implementation for that extension to NSArray
typedef BOOL (^BlockPredicate) (id element);
-(id) detect:(BlockPredicate) predicateBlock{
for (id each in self) {
if (predicateBlock(each)) {
return each;
}
}
return nil;
}
I find this kind of tools really helpful. I hope you find them useful too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With