问题描述:

I'm at the beginning of Objective-C and I'm clueless about my problem

I have a class and I want to filter from an NSArray that includes different instances of class Employee just one variable of instances, 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;

}

网友答案:

To get a list of employees, filtered by name, use

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

To get an array containing only the employee names, use

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

This array can be filtered using

NSPredicate *bPredicate2 = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", @"I"];
NSArray *beginWith2 = [namesOnly filteredArrayUsingPredicate:bPredicate2];
相关阅读:
Top