2013-04-21 39 views
0

我在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

如果您需要更多信息,請讓我知道! - 否則,如果答案有幫助,您可以通過點擊複選標記來「接受」它。這標誌着問題已經解決,併爲您和答案的作者提供了一些「聲譽點」。 – 2013-04-22 19:54:20

回答

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]; 
相關問題