gpt4 book ai didi

objective-c - Objective-C 中的嵌套数组 (NSMutableArray)

转载 作者:搜寻专家 更新时间:2023-10-30 19:51:37 25 4
gpt4 key购买 nike

我正在尝试构建一个嵌套数组:首先,我制作了一个包含 10 个数组的“PlayerItems”数组,每个数组包含项目对象,对应于游戏中每个玩家的库存。在指示的行上,我收到以下错误:

error: void valued not ignored as it ought to be

这里的void值是多少?如果我改用 [[PlayerItems objectAtIndex:i] addObject:myitem],程序会编译但会崩溃。如果我注释掉该行,它会编译并运行正常。感谢您的帮助!

self.PlayerItems = [[NSMutableArray alloc] initWithCapacity:11];
NSMutableArray *itemarray = [[NSMutableArray alloc] initWithCapacity:60];
item *myitem = [[item alloc] init];
item.kind = 1;
for (int i = 1; i < 10; i++) {
itemarray = [[NSMutableArray alloc] initWithCapacity:60];
[PlayerItems addObject:itemarray];
for (int i2 = 1; i2 < 50; i2++) {
myitem = [[item alloc] init];
myitem.kind = 1;
// The error occurs on the line below:
((NSMutableArray *) [[PlayerItems objectAtIndex:i] addObject:myitem]);
}
}

最佳答案

我会这样做:

self.playerItems = [[NSMutableArray alloc] initWithCapacity:11];

NSMutableArray * itemArray;
Item * anItem;
for (int playerIndex = 1; playerIndex <= 10; playerIndex++)
{
itemArray = [NSMutableArray arrayWithCapacity:60];
[playerItems addObject:itemArray];

for (int itemIndex = 1; itemIndex <= 50; itemIndex++)
{
anItem = [[Item alloc] init];
anItem.kind = 1;
[itemArray addObject:anItem];
[anItem release];
}
}

作为旁注,您绝对应该阅读 memory management in Cocoa ,因为您的原始代码充满了内存泄漏。一开始可能有点难以理解,但一旦你学会了,它就会成为第二天性。非常值得付出努力。

更新:

一个更面向对象的方法是创建一个 Player 类,并让每个 Player 管理自己的项目集:

Player.h

@interface Player : NSObject
{
NSMutableArray * items;
}
@property (readonly) NSMutableArray * items;
@end

Player.m

#import "Player.h"
@implementation Player

@synthesize items;

- (id)init
{
if ((self = [super init]) == nil) { return nil; }

items = [[NSMutableArray alloc] initWithCapacity:60];
Item * anItem;
for (int itemIndex = 1; itemIndex <= 50; itemIndex++)
{
anItem = [[Item alloc] init];
anItem.kind = 1;
[items addObject:anItem];
[anItem release];
}

return self;
}

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

@end

别处

NSMutableArray * allPlayers = [[NSMutableArray alloc] initWithCapacity:11];

Player * aPlayer;
for (int playerIndex = 1; playerIndex <= 10; playerIndex++)
{
aPlayer = [[Player alloc] init];
[allPlayers addObject:aPlayer];
[aPlayer release];
}

...

[allPlayers release];

关于objective-c - Objective-C 中的嵌套数组 (NSMutableArray),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1244833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com