将2d int数组添加到NSDictionary

时间:2009-09-05 03:59:25

标签: objective-c arrays int nsdictionary nsmutabledictionary

我是Objective C的新手,并且在向NSMutableDictionary添加2d int数组时遇到了麻烦。 “不兼容的指针类型”的代码错误 - 我认为这是因为setObject会期待一个对象..

以下是代码 - 我正在尝试使用包含我的关卡数据的词典:

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

我有两个问题:

  • 如何将int数组(或类似数据)添加到字典中?
  • 有没有更好的方法来初始化我的游戏数据?

感谢您的帮助,

拉​​克伦

1 个答案:

答案 0 :(得分:1)

您只能将Objective-C对象添加到NSDictionary / NSMutableDictionary,您不能只添加任意指针。如果要将其添加到NSDictionary中,则需要使用NSArray。

您可以创建一个新的“Level”对象并使用访问器管理tiles数组,而不是使用NSMutableDictionary作为关卡对象,因为您无法直接获取/设置C数组。

@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

然后你可以这样做:

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