how to add nil to nsmutablearray?

拥有回忆 提交于 2019-11-28 18:07:30
mr-sk

You can't add nil when you're calling addObject.

Adrian Kosmaczewski

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]];
Mike Weller

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.

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

nil is used to terminate the array

mert

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.

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

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.

pass your object through this method when adding to array to avoid attempt to insert nil object from objects crashes.

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

[NSNull null] returns an null object which represents nil.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!