how to add nil to nsmutablearray?

后端 未结 9 1270
-上瘾入骨i
-上瘾入骨i 2020-12-13 12:22
NSArray *array = [[NSArray alloc] initWithObjects:@\"ΕΛΤΑ\",
                      @\"ΕΛΤΑ COURIER\", @\"ACS\", @\"ACS ΕΞΩΤΕΡΙΚΟ\", 
                      @\"DHL\",          


        
相关标签:
9条回答
  • 2020-12-13 12:47

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

    0 讨论(0)
  • 2020-12-13 12:49

    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.

    0 讨论(0)
  • 2020-12-13 12:55

    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.

    0 讨论(0)
  • 2020-12-13 12:57

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

    0 讨论(0)
  • 2020-12-13 13:01

    nil is used to terminate the array

    0 讨论(0)
  • 2020-12-13 13:04

    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.

    0 讨论(0)
提交回复
热议问题