我有四个数组如下:
toArray = [[NSMutableArray alloc] initWithObjects:@"to 1",@"to 2",@"to 3",@"to 4",@"to 5",@"to 6",@"to 7",nil];
fromArray = [[NSMutableArray alloc] initWithObjects:@"from 1",@"from 2",@"from 3",@"from 4",@"from 5",@"from 6",@"from 7",nil];
messageArray = [[NSMutableArray alloc] initWithObjects:@"message 1",@"message 2",@"message 3",@"message 4",@"message 5",@"message 6",@"message 7",nil];
dayArray = [[NSMutableArray alloc] initWithObjects:@"day 1",@"day 2",@"day 3",@"day 4",@"day 5",@"day 6",@"day 7",nil];
我想复制或创建一个应该包含所有这4个数组的数组。 我怎样才能实现它?
答案 0 :(得分:5)
你的问题有点含糊不清;你想怎么样?
NSMutableArray *completeArray = [NSMutableArray array];
[completeArray addObjectsFromArray:toArray];
[completeArray addObjectsFromArray:fromArray];
[completeArray addObjectsFromArray:messageArray];
[completeArray addObjectsFromArray:dayArray];
或者
NSMutableArray *completeArray = [NSMutableArray arrayWithObjects:toArray, fromArray, messageArray, dayArray, nil];
或者,如果所有数组都具有相同数量的元素:
NSMutableArray *completeArray = [NSMutableArray array];
for (NSUInteger i = 0; i < [toArray count]; i++)
{
NSString *fullString = [NSString stringWithFormat:@"%@ %@ %@ %@", [toArray objectAtIndex:i], [fromArray objectAtIndex:i], [messageArray objectAtIndex:i], [dayArray objectAtIndex:i]];
[completeArray addObject:fullString];
}
或者,作为一个字典数组(也假设所有数组都是相同的长度):
NSMutableArray *completeArray = [NSMutableArray array];
for (NSUInteger i = 0; i < [toArray count]; i++)
{
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[toArray objectAtIndex:i], @"to",
[fromArray objectAtIndex:i], @"from",
[messageArray objectAtIndex:i], @"message",
[dayArray objectAtIndex:i], @"day",
nil];
[completeArray addObject:dict];
}
答案 1 :(得分:1)
这应该有效:
NSArray *singleArray = [NSArray arrayWithElements:toArray, fromArray, messsageArray, dayArray, nil];
// mind the nil element at the end
答案 2 :(得分:1)
NSMutableArray *result = [NSMutableArray arrayWithCapacity:0];
[result addObjectsFromArray:toArray];
[result addObjectsFromArray:fromArray];
[result addObjectsFromArray:messageArray];
[result addObjectsFromArray:dayArray];