Xi Zhu
Xi Zhu

Reputation: 321

Objective C NSMutableArray work with nil

I want to create a NSMutableArray to represent a game board that holds grid element (assume I have a chess class). In this case, I already know the size of the board so I want to create an array by initWithCapacity:[size] and then initialize them as nil. During the game, I may insert or remove chess object into/from this array based on game. I need to check if some cell is nil sometimes.

Clearly initWithCapacity only allocate memory, but gives an empty array whose element is not assessable. I think insert [NSNull null] one by one is inefficient (I can turn to use 0 to represent nil but still not what I want).

Is there any type/structure in Objective C like a C/C++ array for my purpose? Or is it wise to use C/C++ array here? (e.g. Chess myArray[size])

Upvotes: 0

Views: 1452

Answers (2)

James Webster
James Webster

Reputation: 32066

It is by design that NSMutableArrays and other collections do not permit nil and [NSNull null] is used as a placeholder for the concept of "nothing" instead.

I think insert [NSNull null] one by one is inefficient

[NSNull null] is a singleton, so won't allocate lots of memory unnecessarily and is not inefficient.

This answer has more information.


Anther efficiency I'm concerning about [NSNull null] is when I first create the array, if this array is kind of large (say 100 entries)

100 elements isn't a problem. Your device will be able to iterate 100 elements very quickly. Time it if you like.

is enumeration the only way I can assign a nil to each of these 100 entries? (e.g. for (i=0;i<size;i++) {[myArray addObject:[NSNull null]];}

It's the first way I would think of doing it.


"Premature optimisation is the root of all evil"
Donald Knuth

You seem to be concentrating on optimisation too early. You should favour readability over efficiency at this point.

When your app seems to slow down, or near the end of a release, profile the application and find out what, if any problems exist. Otherwise you may find yourself spending a day "optimising" a for loop to find that you've saved 0.000001s per update.

Moreover, readable code is easier to:

  • debug
  • update
  • maintain
  • share

Micro-optimised code takes longer to produce, is prone to bugs, difficult to debug and maintain and often impossible to share as another developer may not know how to interpret your optimisations.

That's not to say "don't optimise", rather concentrate on optimising the biggest problems.

Upvotes: 2

Igor Leonovich
Igor Leonovich

Reputation: 517

You can use something like this:

NSMutableArray *array = [NSMutableArray arrayWithArray:@[@"First", @"Second", @"Third"]];
[array addObject:[NSNull null]];

[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if (![obj isKindOfClass:[NSNull class]]) {
        // Do something
    }
}];

Upvotes: 0

Related Questions