从具有许多实例的NSArray中过滤一个变量

时间:2013-04-21 11:23:42

标签: objective-c arrays nspredicate

我在Objective-C的开头,我对我的问题一无所知

我有一个课程,我希望从包含NSArray个不同实例的Employee过滤一个实例变量name

Employee.h

#import <Foundation/Foundation.h>

@interface Employee : NSObject
@property NSString *name ;
@property int age;
@end

Employee.m

#import "Employee.h"

@implementation Employee
@synthesize name ;
@synthesize age;
@end

的main.m

#import <Foundation/Foundation.h>
#import "Employee.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Employee *firstEmployee = [[Employee alloc] init];
        [firstEmployee setAge:35];
        [firstEmployee setName:[NSString stringWithFormat:@"George "]];

        Employee *secondEmployee = [[Employee alloc] init];
        [secondEmployee setAge:35];
        [secondEmployee setName:[NSString stringWithFormat:@"Ivan "]];

        Employee *thirdEmployee = [[Employee alloc] init];
        [thirdEmployee setAge:35];
        [thirddEmployee setName:[NSString stringWithFormat:@"Ivan "]];

        NSMutableArray *yesArray =                                                         
        [NSMutableArray arrayWithObjects:firstEmployee, secondEmployee, thirdEmployee, nil];
        int i;
        int count;
        count = [yesArray count];

        for (i = 0; i < count; i++){
            NSLog(@"Name of %i is %@", i, [[yesArray objectAtIndex:i] name]);
            NSLog(@"Age of  %i is %i", i, [[yesArray objectAtIndex:i] age]);
            NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'j'"];
            // I don't know how to access just name
            NSArray *beginWithB = [[yesArray name]  filteredArrayUsingPredicate:bPredicate]; 
         }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:2)

要获取按名称过滤的员工列表,请使用

NSPredicate *bPredicate1 = [NSPredicate predicateWithFormat:@"name BEGINSWITH[c] %@", @"I"];
NSArray *beginWith1 = [yesArray filteredArrayUsingPredicate:bPredicate1];

要获取仅包含员工姓名的数组,请使用

NSArray *namesOnly = [yesArray valueForKey:@"name"];

可以使用

过滤此数组
NSPredicate *bPredicate2 = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", @"I"];
NSArray *beginWith2 = [namesOnly filteredArrayUsingPredicate:bPredicate2];