views:

538

answers:

1

Hello - I am new to Objective C and am having troubles adding a 2d int array to a NSMutableDictionary. The code errors with "incompatible pointer type" - I assume this is because setObject would be expecting an object..

Here is the code - I am trying to have a Dictionary containing my level data:

NSMutableDictionary *level = [[NSMutableDictionary alloc] init];

[level setObject:@"The Title" forKey:@"title"];
[level setObject:@"level_1" forKey:@"slug"];

int levelTiles[10][10] = {
 {1,1,1,1,1,1,1,1,1,1},
 {1,0,0,0,0,0,0,0,0,1},
 {1,0,0,0,0,0,0,0,0,1},
 {1,0,0,0,0,0,0,0,0,1},
 {1,0,0,0,0,0,0,0,0,1},
 {1,0,0,0,0,0,0,0,0,1},
 {1,0,0,0,0,0,0,0,0,1},
 {1,0,0,0,0,0,0,0,0,1},
 {1,0,0,0,0,0,0,0,0,1},
 {1,1,1,1,1,1,1,1,1,1}
};


[level setObject:levelTiles forKey:@"tiles"]; // THIS LINE FAILS

I have 2 questions:

  • How do I add the int array (or similar) to the dictionary like this?
  • Is there a better way to initialise the data for my game?

Thanks for your help,

Lachlan

+1  A: 

You can only add Objective-C objects to an NSDictionary/NSMutableDictionary, you can't just add any arbitrary pointer. You'd need to use an NSArray if you wanted to add it to an NSDictionary.

Rather than using an NSMutableDictionary for your level object, you could create a new "Level" object and manage the tiles array using accessors, as you can't get/set C arrays directly.

@interface Level : NSObject 
{
    NSString* title;
    NSString* slug;
    int levelTiles[10][10];  
}
- (id)initWithTitle:(NSString*)aTitle slug:(NSString*)aSlug tiles:(int[10][10])tiles;
- (int)valueOfTileAtI:(int)i j:(int)j;
- (int)setI:(int)i j:(int)j to:(int)v;
@end

@implementation Level
- (id)initWithTitle:(NSString*)aTitle slug:(NSString*)aSlug tiles:(int[10][10])tiles 
{
    self=[super init];
    if(self)
    {
        title = [aTitle copy];
        slug = [aSlug copy];
        for (int i=0; i<10; i++) 
        {
            for (int j=0; j<10; j++) 
            {
                levelTiles[i][j] = levelTiles[i][j];
            }
        }
    }
    return self;
}

- (int)valueOfTileAtI:(int)i j:(int)j 
{
    return levelTiles[i][j];
}

- (void)setTileAtI:(int)j j:(int)j toValue:(int)v 
{
    levelTiles[i][j] = v;
}

-(void)dealloc
{
    [title release];
    [slug release];
    [super dealloc];
}

@end

You could then do this:

int tiles[10][10] = {
        {1,1,1,1,1,1,1,1,1,1},
        {1,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,1},
        {1,0,0,0,0,0,0,0,0,1},
        {1,1,1,1,1,1,1,1,1,1}
};
Level* myLevel = [[Level alloc] initWithTitle:@"The Title" slug:@"level_1" tiles:tiles];
Rob Keniger
That's very helpful. Thanks Rob
Loks