Search code examples
iosobjective-cnullnsarray

remove row in array if value is NULL in Objective C


how to remove empty or Null value from Nsarray in objective c

here my sample code :

cell.subtitleLbl.text = [[chapterArray objectAtIndex:indexPath.row] valueForKey:@"person"];

Solution

  • Choice-1

    // mainArray array is your current array
    NSMutableArray *tempArray = [[NSMutableArray alloc]init];
    for (int i = 0; i < [mainArray count]; i++) {
        id obj = [mainArray objectAtIndex:i];
        if (![obj  isKindOfClass:[NSNull class]]) { // or if (![obj  isKindOfClass:[[NSNull null]class]]) {
            [tempArray addObject:obj];
        }
    }
    
    NSLog(@"%@",tempArray);
    

    Choice-2

    [yourarrayName removeObjectIdenticalTo:[NSNull null]];
    

    Choice-3

    ussing Predicate

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (SELF CONTAINS %@)", @"<null>"];
    [yourarrayname filterUsingPredicate:predicate];
    

    Choice-4

    if you using array of dictionary

    NSMutableArray *newarray=[NSMutableArray array];
    for (NSDictionary *dictionary in presentArrray)
    {
        if (dictionary[key] != [NSNull null]) {
            [newarray addObject:dictionary];
        }
    }