views:

924

answers:

8
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 at cellForRowAtIndexPath:

how can I do this work?

Ok, I dont have to add nil

What is the reason that my app crashes then?

A: 

You don't have add the nil when your calling addObject:

Mr-sk
+5  A: 

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.

Mike Weller
Also, 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.
Nimrod
+1  A: 

nil is not an object that you can add to an array: An array cannot contain nil. This is why addObject:nil crashes.

mouviciel
A: 

nil is used to terminate the array

Tomen
A: 

You can't add an object to an NSArray because that class is immutable. You have to use NSMutableArray if you want to change the array after it is created.

TechZen
A: 

In the example, you're creating an NSArray, not a mutable array. If you try to use addObject: on this array, the app will crash (and the complier will warn you, read the warnings!).

If this is not the problem you'll have to show us more code, we're no fortunetellers. ;)

Pascal
+6  A: 

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]];
Adrian Kosmaczewski
A: 

If you really want a Null-ish item in your collection, NSNull is there for that.

David Grant