简体   繁体   English

Objective C二维数组内存问题

[英]Objective C two-dimensional array memory issues

I'm trying to declare a two-dimensional array as an instance variable in Objective C. I've got the NSMutableArray in the header (data), along with the @property (nonatomic, retain). 我试图在对象C中声明一个二维数组作为实例变量。我在标题(数据)中带有NSMutableArray,以及@property(非原子性,保留)。 In viewDidLoad: I have: 在viewDidLoad中:我有:

data = [[NSMutableArray alloc] init];
[data addObject:[[NSArray alloc] initWithObjects:@"Cheese", @"Meat", @"Veggie", nil]];
[data addObject:[[NSArray alloc] initWithObjects:@"Sandwich", @"Soup", @"Stew", nil]];

I can NSLog the array within the method and it is correct, however when I try to Log it from a separate method I get nothing (just "@"), and if I try to access with 我可以在方法中使用NSLog数组,这是正确的,但是当我尝试从单独的方法中记录它时,我什么也没得到(只是“ @”),并且如果我尝试使用

NSInteger num = [[data objectAtIndex:component] count];

it crashes with no error in the log. 它崩溃,日志中没有错误。 I'm sure this is something to do with not allocating memory properly, however I am new to Obj C and haven't worked with a C-style language in many years. 我确定这与未正确分配内存有关,但是我是Obj C的新手,并且多年来没有使用C风格的语言。 FWIW, I have tried many variants of this that all fail, including using NSArray instead of mutable, [NSArray arrayWithObjects] instead of [[NSArray alloc] initWithObjects], and every combination in between. FWIW,我已经尝试了许多这样的变体,但都失败了,包括使用NSArray而不是可变的,使用[NSArray arrayWithObjects]代替[[NSArray alloc] initWithObjects],以及两者之间的每种组合。

尝试像这样创建外部数组:

 self.data = [NSMutableArray arrayWithCapacity:2];  // assuming you're only adding 2 inner arrays.

The following may be a right way. 以下可能是正确的方法。

self.data = [NSMutableArray array];
[data addObject:[NSArray arrayWithObjects:@"Cheese", @"Meat", @"Veggie", nil];
[data addObject:[NSArray arrayWithObjects:@"Sandwich", @"Soup", @"Stew", nil];

Note that, as @jamihash commented above, you need self.data to properly retain the array . 请注意,正如上面的@jamihash所述, 您需要self.data才能正确保留array And, there is no need to alloc the NSArray which you are adding to data . 而且,也没有必要allocNSArray ,你要添加到data

As a side issue, you're retaining the child arrays twice. 附带的问题是,您将子数组保留两次。 They get retained when you add them to your NSMutableArray, so you should probably autorelease them on creation or create them with one of the NSArray methods that returns an autoreleased array. 当您将它们添加到NSMutableArray中时,它们会保留下来,因此您可能应该在创建时自动释放它们,或者使用返回自动释放数组的NSArray方法之一创建它们。

Your code by itself shouldn't crash. 您的代码本身不应该崩溃。 You should look into where and when you release and retain the NSMutableArray. 您应该研究释放和保留NSMutableArray的位置和时间。 You could post more of the code and I'm sure somebody will spot the problem. 您可以发布更多代码,我敢肯定有人会发现问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM