I know Apple is big on having you use NS objects instead of true primitive types, but I need the capabilities of an array (namely direct access of items at indices). However, it seems that they are so very keen on using NS objects that I can’t find a single tutorial online or in a textbook about how to use basic primitive arrays. I want something that does things like this does in Java:
String inventory[] = new String[45];
inventory[5] = "Pickaxe";
inventory[12] = "Dirt";
inventory[8] = "Cobblestone";
inventory[12] = null;
System.out.println("There are " + inventory.length + " slots in inventory: " + java.util.Arrays.toString(inventory));
The following is the closest I’ve gotten in Objective-C, but it won’t run properly:
NSString *inventory[45];
inventory[5] = @"Pickaxe";
inventory[12] = @"Dirt";
inventory[8] = @"Cobblestone";
inventory[12] = nil;
NSArray *temp = [NSArray arrayWithObjects:inventory count:45];
NSLog(@"There are %i slots in inventory: %@", [temp count], [temp description]);
Also, if at all possible, is there something in O-C that will give me the count of non-null/non-nil objects in the array? (This way, I can tell how much space is left in the inventory so that the player can’t pack away anything if it’s full)
typically, you would use
NSArray/NSMutableArray, although you could also use C arrays.NSArray(and most Foundation collections) cannot containnilentries – you can useNSPointerArray(OS X) if you neednilvalues, or simply use[NSNull null]in anNSArrayto designatenil.Here’s your program using an
NSArray:An NSArray is a CFArray – they are “toll free bridged”. Use
CFArrayGetCountOfValuewith[NSNull null]as the value to seek. Most of the CF-APIs are available in the NS-APIs, but not this one. You could easily wrap it in a category, if needed often.