代码之家  ›  专栏  ›  技术社区  ›  elcool codeVerine

@implementation NSArray(Find)到底是什么及其发出的警告?

  •  0
  • elcool codeVerine  · 技术社区  · 14 年前

    @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-查找做什么?在执行这些实现时,我看到过其他类似的词,那么它到底在做什么呢?是关键字,还是只是让我知道?

    我从这里得到了密码: http://probablyinteractive.com/2009/2/13/keypaths.html 但当我把它放在我的项目上并称之为

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

    它返回警告 “NSArray”可能不响应“-findAllWhereKeyPath:equals:” 如果我运行它,它就会崩溃。

    1 回复  |  直到 14 年前
        1
  •  0
  •   kovpas    14 年前
    1. 此方法返回包含值对象的所有键路径。

    2. 创建NSArray(Find).h和NSArray(Find).m文件:

    NSArray(查找).h:

    #import <Foundation/Foundation.h>
    
    @interface NSArray(Find)
    - (NSArray *)findAllWhereKeyPath:(NSString *)keyPath equals:(id)value;
    @end
    

    @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;
    }
    

    两个文件都应该添加到项目中。将NSArray(Find).h导入.m文件,在其中使用您的类别:

    #import "NSArray(Find).h"
    

    findAllWhereKeyPath:equals: 那就行了。