how to add nil to nsmutablearray?
Solution 1
You can't add nil when you're calling addObject
.
Solution 2
If you must add a nil
object to a collection, use the NSNull
class:
The NSNull class defines a singleton object used to represent null values in collection objects (which don’t allow nil values).
Assuming "array" is of type NSMutableArray:
....
[array addObject:[NSNumber numberWithInt:2];
[array addObject:@"string"];
[array addObject:[NSNull null]];
Solution 3
You don't need to call [addObject:nil]
The nil
in initWithObjects:
is only there to tell the method where the list ends, because of how C varargs
work. When you add objects one-by-one with addObject:
you don't need to add a nil.
Solution 4
If you really want a Null-ish item in your collection, NSNull is there for that.
Solution 5
You need to add NSNull
class and the best way to do it is like this:
NSArray *array = @[ @"string", @42, [NSNull null] ];
I personally recommend to use a specific value like 0
instead of null or nil in your design of your code, but sometimes you need to add null.
There is a good explanation from this Apple reference.
Comments
-
stefanosn almost 2 years
NSArray *array = [[NSArray alloc] initWithObjects:@"ΕΛΤΑ", @"ΕΛΤΑ COURIER", @"ACS", @"ACS ΕΞΩΤΕΡΙΚΟ", @"DHL", @"INTERATTICA", @"SPEEDEX", @"UPS", @"ΓΕΝΙΚΗ ΤΑΧΥΔΡΟΜΙΚΗ", @"ΜΕΤΑΦΟΡΙΚΕΣ ΕΞΩΤΕΡΙΚΟΥ", nil];
This is working because it has nil at the end.
But I add objects like this:
addObject:name
etc... So at the end I have to add nil I do this addObhect:nil but when I run the app it still crashes atcellForRowAtIndexPath:
how can I do this work?
Ok, I dont have to add nil
What is the reason that my app crashes then?
-
Nimrod over 14 yearsAlso, the nil is called a "sentinel" because it "guards" the end of the list so that things don't iterate off of the end. It's worth knowing that it's called a sentinel because you may see a compiler error/warning like "missing sentinel value ...". In this case it means you forgot a nil at the end of something, usually a list after initWithObjects.
-
Supertecnoboff about 9 yearsSo basically if you are add using the
addObjects
method on a NSMutableArray, you don't need to add anil
at the end? It just knows when it reaches the end itself? -
tmr almost 9 yearsfor new folks (me), example of test to see if array element equals the inserted nil value, 'if ([self.voice objectAtIndex:indexPath.row] != [NSNull null]) {' (thank you akosma)