合并NSArrays以使用对象创建新数组

时间:2014-12-13 12:50:41

标签: objective-c nsarray

我有3个NSArrays,每个NSArrays有6个对象:

NSArray *A [Joe, John, Jay, Jason, Jonah, Jeremiah];
NSArray *B [Doe, Smith, Scott, Jackson, Johnson, Lewis];
NSArray *C [1,2,3,4,5,6];

我的模特是:

@interface Person : NSObject

@property NSString *firstName;
@property NSString *lastName;
@property NSString *number;

@end

我需要创建一个第四个数组,其中每个人对象都有一个firstName,lastName,数字。

NSArray *D = [0]Joe, Doe, 1
             [1]John, Smith, 2 
             [2]Jay.Scott,3  
             [3]Jason, Jackson, 4
             [4]Jonah, Johnson, 5
             [5]Jeremiah. Lewis, 6

我该怎么做?

2 个答案:

答案 0 :(得分:3)

您可以执行以下操作:(在旁注中,请使用适当的属性声明您的类属性)

NSArray *A = @[@"Joe", @"John", @"Jay", @"Jason", @"Jonah", @"Jeremiah"];
NSArray *B = @[@"Doe", @"Smith", @"Scott", @"Jackson", @"Johnson", @"Lewis"];
NSArray *C = @[@1, @2, @3, @4, @5, @6];

NSMutableArray *D = [[NSMutableArray alloc] initWithCapacity:A.count];

for (int i=0; i < A.count; i++)
{
    Person *p = [[Person alloc] init];
    p.firstName = [A objectAtIndex:i];
    p.lastName = [B objectAtIndex:i];
    p.number = [C objectAtIndex:i];

    [D addObject:d];
}

让我知道它是怎么回事。

答案 1 :(得分:-1)

尝试将enumerateObjectsUsingBlock用于数组: -

NSArray *A = @[@"Joe", @"John", @"Jay", @"Jason", @"Jonah", @"Jeremiah"];
NSArray *B = @[@"Doe", @"Smith", @"Scott", @"Jackson", @"Johnson", @"Lewis"];
NSArray *C = @[@1, @2, @3, @4, @5, @6];

NSMutableArray *mutArr=[NSMutableArray array];
[A enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
 Person *p=[[Person alloc]init];
    p.firstName=A[idx];
    p.lastName=B[idx];
    p.number=C[idx];
    [mutArr addObject:p];
}];
NSLog(@"person=%@",mutArr);