0

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

我有一个类,我想从一个NSArray包含不同类实例的类中过滤一个实例Employee变量,name

员工.h

#import <Foundation/Foundation.h>

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

员工.m

#import "Employee.h"

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

主文件

#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;
}
4

1 回答 1

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];
于 2013-04-21T11:47:47.410 回答