开发者

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). In viewDidLoad: I have:

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

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

it crashes with no error in the log. I'm sure this is something to do with not al开发者_StackOverflowlocating memory properly, however I am new to Obj C and haven't worked with a C-style language in many years. 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.


try creating the outer array like this:

 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. And, there is no need to alloc the NSArray which you are adding to 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.

Your code by itself shouldn't crash. You should look into where and when you release and retain the NSMutableArray. You could post more of the code and I'm sure somebody will spot the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜