Tuesday, 14 May 2013

Code For NSPredicate in objective c(IOS)


    Add a new file(NSObject) in your working application and add following code first..

.h

-(id)initWithName:(NSString *) name;
-(NSString *)description;


.m

@synthesize strName;

-(id)initWithName:(NSString *) name
{
    self = [super init];
    if(self)
    {
        self.strName = [name copy];
        
        
    }
    return self;
}

-(NSString *)description
{
    return self.strName;
}

After that import this file in your desired view and add Following piece of code..




    Employee *emp = [[Employee alloc]initWithName:@"Amit"];
    Employee *emp1 = [[Employee alloc]initWithName:@"Sudheer"];
    Employee *emp3 = [[Employee alloc]initWithName:@"Kiran"];
    
    NSMutableArray *arr1  = [[NSMutableArray alloc]initWithObjects:emp,emp1,emp3 ,nil];
    
    
    NSPredicate *nsPred1 = [NSPredicate predicateWithFormat:@"strName == 'Kiran'"];
    NSPredicate *nsPred2 = [NSPredicate predicateWithFormat:@"strName.length <5"];
    NSPredicate *nsPred3 = [NSPredicate predicateWithFormat:@"strName BEGINSWITH[c] 'a'"];
    NSPredicate *nsPred4 = [NSPredicate predicateWithFormat:@"strName ENDSWITH[c] 'r'"];
    
    NSArray *arrFilterdArray1 = [arr1 filteredArrayUsingPredicate:nsPred1];
    NSArray *arrFilterdArray2 = [arr1 filteredArrayUsingPredicate:nsPred2];
    NSArray *arrFilterdArray3 = [arr1 filteredArrayUsingPredicate:nsPred3];
    NSArray *arrFilterdArray4 = [arr1 filteredArrayUsingPredicate:nsPred4];
    NSLog(@"%@",arrFilterdArray1);
    NSLog(@"%@",arrFilterdArray2);
    NSLog(@"%@",arrFilterdArray3);
    NSLog(@"%@",arrFilterdArray4);


Out Put


2013-05-15 11:50:26.918 StoryBoardApplication[390:207] (
    Kiran
)
2013-05-15 11:50:28.037 StoryBoardApplication[390:207] (
    Amit
)
2013-05-15 11:50:28.661 StoryBoardApplication[390:207] (
    Amit
)
2013-05-15 11:50:29.276 StoryBoardApplication[390:207] (
    Sudheer
)

No comments:

Post a Comment