2010-04-07 95 views
8

是否有一种方法来创建二维NSArray,而不需要以原始格式aFloatArray [] []嵌套数组。多维NSArray对象

谢谢。

+3

什么是你需要完成的?也许可能有其他方法更适合您正在解决的问题。 – jlehr 2010-04-07 23:51:08

回答

17

不幸的不是。要创建一个多维的NSArray:

NSArray *multiArray = [NSArray arrayWithObjects: 
    [NSMutableArray array], 
    [NSMutableArray array], 
    [NSMutableArray array], 
    [NSMutableArray array], nil]; 

// Add a value 
[[multiArray objectAtIndex:1] addObject:@"foo"]; 

// get the value 
NSString *value = [[multiArray objectAtIndex:1] objectAtIndex:0]; 

但是,您可以在Objective-C用C代码(因为它是C严格的超集),如果它符合你的需要,你有,你可以声明数组建议。

+6

如果你没有使用垃圾收集,那么你在'multiArray'中泄漏每个数组。要修复,请改用'[NSMutableArray array]'。 – 2010-04-08 00:34:21

+0

真的吗?这是我的理解,[NSMutableArray数组]返回一个自动释放的NSMutableArray,这反过来将被添加到它的NSArray保留! 我会明确地看看,因为如果你是正确的,我有很多代码去通过lol – FatalMojo 2010-04-08 04:31:25

+1

是的。重点是自动释放的对象_is_被它添加到的数组保留。当父数组被释放时,其内容也是如此。如果将'[NSMutableArray new]'添加到数组中,则其保留计数变为'2'。当父数组被释放时,它的每个孩子仍然有一个保留计数“1”。 – 2010-04-08 06:18:00

10

你可以这样做:

NSArray *array = @[@[@"0:0", @"0:1"], 
        @[@"1:0", @"1:1"]]; 

NSString *value = array[1][0]; 

我认为这是比 “objectAtIndex” 的东西要短得多。

但要注意,你必须使用苹果LLVM编译器版本> = 4.0

+0

这绝对是现代的方法。 – 2014-05-09 09:06:15

0

插入在收集或TableView中的cellForRowAtIndexPath多维数组的对象:

NSString *sectionRow = [NSString stringWithFormat:@"%d:%d", indexPath.section, indexPath.row];     
[dictionary setValue:[UIImage imageWithData:imageData] forKey:sectionRow]; 

要收集检索多维数组的对象或TableView cellForRowAtIndexPath:

NSString *sectionRow = [NSString stringWithFormat:@"%d:%d", indexPath.section, indexPath.row];  
UIImage *cellImage = [dictionary valueForKey:sectionRow];