Search code examples
iosobjective-cnsmutablearraynsnull

NSMutableArray removing Nulls


From my JSON feed i create a NSMutableArray to hold my NDDictionary objects. When I come to display this in a UITableView it crashes due to <null> Values. So I need to know, How exactly can i remove these "<null>" Objects from my Array.

Here is a print out of what is returned from the JSON:

Service Names: (
"Nether Edge to Woodhouse",
"Barnsley to Rotherham",
"Woodhouse to Nether Edge",
"Rotherham to Barnsley",
"Doncaster to Worksop",
"Worksop to Doncaster",
"Penistone to Barnsley Interchange",
"Barnsley Interchange to Penistone",
"<null>",
"Barnsley to Rotherham",
"Rotherham to Barnsley",
"<null>",
"Buttershaw to St Bedes RC Upper School",
"St Bedes RC Upper School to Buttershaw",
"<null>",
"Sandholme Drive to Ilkley GS",
"Ilkley GS to Sandholme Drive",
"<null>",
"Barnsley to Rotherham",
"Rotherham to Barnsley"
)

I have tried things such as :

[serviceNames removeObject:@"<null>"];
[serviceNames removeObject:[NSNull null]];

and

[serviceNames removeObjectsIdenticalTo:@"<null>"];
[serviceNames removeObjectsIdenticalTo:[NSNull Null]];

All which have failed up to now so can anybody please tell me a simple way of removing the "<null>"objects from this array as its driving me mad!


Solution

  • Try this,
    Note: this I not tested.

    tempArray is your real array.

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