将 2d int 数组添加到 NSDictionary
我是 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
我有 2 个问题:
- 如何添加int 数组(或类似的)像这样的字典?
- 有没有更好的方法来初始化我的游戏数据?
感谢您的帮助,
拉克兰
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只能将 Objective-C 对象添加到 NSDictionary/NSMutableDictionary,而不能只添加任意指针。如果要将 NSArray 添加到 NSDictionary,则需要使用 NSArray。
您可以创建一个新的“Level”对象并使用访问器管理图块数组,而不是使用 NSMutableDictionary 作为关卡对象,因为您无法直接获取/设置 C 数组。
然后你可以这样做:
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.
You could then do this: