views:

31

answers:

1

A couple of questions regarding the following code:

@implementation NSArray (Find)
- (NSArray *)findAllWhereKeyPath:(NSString *)keyPath equals:(id)value {
   NSMutableArray *matches = [NSMutableArray array];
   for (id object in self) {
     id objectValue = [object valueForKeyPath:keyPath];
     if ([objectValue isEqual:value] || objectValue == value) [matches addObject:object];         
   }
   return matches;
}

1- What does (Find) do? I've seen other words like this when doing these implementations, so what exactly is it doing? Is it a keyword, or just for me to know?

2- I got the code from here: http://probablyinteractive.com/2009/2/13/keypaths.html But when I place it on my project and call it

NSArray *filterResults = [allResults findAllWhereKeyPath:@"firstname" equals:firstname];

it returns the warning 'NSArray' may not respond to '-findAllWhereKeyPath:equals:' and if I run it, it crashes. I've placed the code at the beginning of the .m, at the .h and changed it to NSMutableArray, but I keep getting the warning. So, how should I solve this?

A: 
  1. This method returns all keyPaths, that contains value object.

  2. To make this category work you should do the following: Create NSArray(Find).h and NSArray(Find).m files:

NSArray(Find).h:

#import <Foundation/Foundation.h>

@interface NSArray(Find)
- (NSArray *)findAllWhereKeyPath:(NSString *)keyPath equals:(id)value;
@end

NSArray(Find).m:

@implementation NSArray (Find)
- (NSArray *)findAllWhereKeyPath:(NSString *)keyPath equals:(id)value {
   NSMutableArray *matches = [NSMutableArray array];
   for (id object in self) {
     id objectValue = [object valueForKeyPath:keyPath];
     if ([objectValue isEqual:value] || objectValue == value) [matches addObject:object];         
   }
   return matches;
}

Both files should be added to your project. Import NSArray(Find).h to the .m file, where you want to use your category:

#import "NSArray(Find).h"

findAllWhereKeyPath:equals: should work then.

kovpas
First question was for the meaning of (Foo). Your answer gave me a warning since it's returning an NSMutableArray and it wants an NSArray.
elcool
@elcool you definitely should read about categories in objective-c: http://macdevelopertips.com/objective-c/objective-c-categories.html. Re NSMutableArray problem - Please post a warning. I don't see any problems here, but if you really want to return non-mutable object you may replace return statement with "return [NSArray arrayWithArray:matches];"
kovpas
Thanks, this solved the problem. I created the .h and .m files and played around with NSMutableArray and NSArray. And yes, I'll read about categories, thanks
elcool