1

我是 Objective C 的新手,在将 2d int 数组添加到 NSMutableDictionary 时遇到了麻烦。“不兼容的指针类型”的代码错误 - 我认为这是因为 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 数组(或类似数组)添加到字典中?
  • 有没有更好的方法来初始化我的游戏数据?

谢谢你的帮助,

拉克兰

4

1 回答 1

1

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

您可以创建一个新的“Level”对象并使用访问器管理切片数组,而不是使用 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];
于 2009-09-05T04:33:57.187 回答