开发者

What exactly is @implementation NSArray (Find) and the Warning it gives?

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];
 开发者_Go百科    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?


  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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜