Search code examples
iosnsmutablearraynsarraynspredicatensnumber

NSPredicate in NSArray, contains number with "/"


I would like to filter NSMutableArray with birthday date of user with Facebook. Can I use NSPredicate ? My NSLog of "result" is :

"birthday": "05/24/1993", 
  "id": "xxxxxxxxxxx""

I would like only "05/24/1993 for getting birthday date and saves that in NSArray : birthday.

Here is my code :

- (void)viewDidLoad
{
    [super viewDidLoad];
    FBRequest *friendRequest = [FBRequest requestForGraphPath:@"/me?fields=birthday"];
    [ friendRequest startWithCompletionHandler:^(FBRequestConnection *connection,id result, NSError *error) {
        [[NSUserDefaults standardUserDefaults]setObject:result forKey:@"birthdayDate"];
        self.birthdayArray=[[NSUserDefaults standardUserDefaults]objectForKey:@"birthdayDate"];

        NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] '/'"];
        self.birthday = [self.birthdayArray filteredArrayUsingPredicate:aPredicate];

        NSLog(@"BIRTHDAY : %@", self.birthday);

    }

and my NSLog of NSArray birthday is ERROR :

-[__NSCFDictionary filteredArrayUsingPredicate:]: unrecognized selector sent to instance 0x10f80a570

Solution

  • Your result is an NSDictionary instance and not an NSArray instance. Thats why you get the error message since NSDictionary does not support the filteredArrayUsingPredicate message.

    You can get an NSArray containing all the keys from the NSDictionary:

    NSArray *keys = [result allKeys];
    

    Filter the array as you did :

    NSArray *filteredKeys = [keys filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"]];
    

    And then use the filteredKeys to extract the required value(s) from the dictionary :

    for (NSString *key in filteredKeys) { // Assuming that the dictionary keys are string
        id value = [result objectForKey:key];
        NSLog(@"Current value for key %@ = %@", key, value);
    }