将数组添加到iOS中的另一个数组

时间:2015-01-28 19:17:08

标签: ios objective-c nsarray

我有一个奇怪的问题因为" addObject"正在努力添加NSString但不添加NSArray

    NSMutableString *starCatalogEntryValue = [[NSMutableString alloc] init]; // a single string from a catalog
    NSMutableArray *starCatalogEntryData = [[NSMutableArray alloc] init]; // array of strings
    NSMutableArray *starCatalogData = [[NSMutableArray alloc] init]; // array of arrays

loop i times {
    [starCatalogEntryData removeAllObjects];
    loop j times {
        [starCatalogEntryData addObject:starCatalogEntryValue]; // This works
    }
    [starCatalogData addObject:starCatalogEntryData]; // This does not work
}

实际上,添加数组starCatalogEntryData有效但不正常。我最终在starCatalogData中输入了i个条目,但它们都等于starCatalogEntryData的最后一个值。

1 个答案:

答案 0 :(得分:3)

问题是你一遍又一遍地重复使用startCatalogEntryData。你想要这个:

NSMutableString *starCatalogEntryValue = [[NSMutableString alloc] init]; // a single string from a catalog
NSMutableArray *starCatalogData = [[NSMutableArray alloc] init]; // array of arrays

loop i times {
    NSMutableArray *starCatalogEntryData = [[NSMutableArray alloc] init]; // array of strings
    loop j times {
        [starCatalogEntryData addObject:starCatalogEntryValue]; // This works
    }
    [starCatalogData addObject:starCatalogEntryData]; // This does not work
}

每次都会创建一个新数组。