How to add nil to nsmutablearray?

NSArray *array = [[NSArray alloc] initWithObjects:@"ΕΛΤΑ", @"ΕΛΤΑ COURIER", @"ACS", @"ACS ΕΞΩΤΕΡΙΚΟ", @"DHL", @"INTERATTICA", @"SPEEDEX", @"UPS", @"ΓΕΝΙΚΗ ΤΑΧΥΔΡΟΜΙΚΗ", @"ΜΕΤΑΦΟΡΙΚΕΣ ΕΞΩΤΕΡΙΚΟΥ", nil]; 

This works because in the end it has zero.

But I add such objects: addObject:name , etc .... Therefore, in the end I have to add nil, I do this addObhect: zero, but when I run the application, it still crashes with cellForRowAtIndexPath:

How can i do this?

Ok i don't need to add nil

What is the reason that my application will work?

+50
null objective-c iphone nsmutablearray
Jan 13 '10 at 15:39
source share
9 answers

You cannot add nil when you call addObject .

+17
Jan 13
source share

If you must add a nil object to the collection, use the NSNull class:

The NSNull class defines a singleton object used to represent null values ​​in collection objects (which do not allow nil values).

Assuming the "array" is of type NSMutableArray:

 .... [array addObject:[NSNumber numberWithInt:2]; [array addObject:@"string"]; [array addObject:[NSNull null]]; 
+225
Jan 13 '10 at 17:03
source share

You do not need to call [addObject:nil]

nil in initWithObjects: only there to tell the method where the list ends, due to how C varargs works. When you add objects one by one using addObject: you do not need to add zero.

+26
Jan 13 '10 at 15:45
source share

If you really need the Null-ish element in your collection, NSNull exists for this.

+15
Jan 13
source share

nil is used to complete the array

+6
Jan 13
source share

nil not an object that can be added to an array: an array cannot contain nil . This is why addObject:nil crashes.

+5
Jan 13 '10 at 16:02
source share

You need to add NSNull , and the best way to do this is:

 NSArray *array = @[ @"string", @42, [NSNull null] ]; 

I personally recommend using a specific value, like 0 instead of zero or zero in your code design, but sometimes you need to add null.

There is a good explanation for this Apple link .

+5
Oct 17 '14 at 15:35
source share

You cannot add an object to an NSArray because this class is immutable. You must use NSMutableArray if you want to modify the array after creating it.

0
Jan 13 '10 at 17:01
source share

pass your object using this method when adding to an array to avoid trying to insert a nil object from objects .

 -(id) returnNullIfNil:(id) obj { return (obj == nil) ? ([NSNull null]) : (obj); } 

[NSNull null] returns a null object that represents nil.

0
Dec 09 '16 at 5:14
source share



All Articles