来自NSArray的NSMutableArray(1 dim)(2dim)

时间:2013-12-07 09:58:49

标签: ios objective-c arrays

我想创建一个包含所有其他数组对象的数组,看起来像这样

 ("052-6224754","03-6475075","02-6753231")

我的代码是:

-(NSMutableArray*) getRecepientsPhones
{
NSMutableArray* phones = [[NSMutableArray alloc]init];
//scroll all choosed contacts and retrieve phones to nsstring
if([recepientsFromContacts count]>0)
    for (int i=0; i<[recepientsFromContacts count]; i++)
    {
        NSMutableArray* tempArray = [[NSMutableArray alloc]init];
        if(![[[recepientsFromContacts objectAtIndex:i]objectForKey:@"CPhones"]isKindOfClass:[NSNull class]])
        {
            [tempArray addObject:[[recepientsFromContacts objectAtIndex:i]objectForKey:@"CPhones"]];
            for(int j = 0; j<[tempArray count];j++)
            {
                [phones addObject:[tempArray objectAtIndex:j]];
            }
        }
    }
//lets fetch from that contact
if([personRecepient count]>0)
{
    if(![[personRecepient objectForKey:@"CellPhone"]isKindOfClass:[NSNull class]])
        [phones addObject:[personRecepient objectForKey:@"CellPhone"]];
}

NSLog(@"%@",phones);
return phones;

}

[[recepientsFromContacts objectAtIndex:i]objectForKey:@"CPhones"]

是1个或更多维度数组(每人的电话号码数组,人数可以超过1个) 例如:(“052-6224754”,“03-6475075”)

但我的函数返回

( “052-6224754”, “03-6475075”),( “02-6753231”)

这不好,我该怎么做才能使它成为1个数组         ( “052-6224754”, “03-6475075”, “02-6753231”)

1 个答案:

答案 0 :(得分:1)

您应该更改

[phones addObject:[tempArray objectAtIndex:j]];

[phones addObjectsFromArray:[tempArray objectAtIndex:j]];

这会导致电话号码变平。

然后你应该转到codereview.stackexchange.com,因为你的代码片段有几个问题。

编辑:以下是该方法的清理版本:

- (NSArray *)recepientsPhoneNumbers
{
    NSMutableArray* phoneNumbers = [NSMutableArray array];

    for (NSDictionary *dict in _recepientsFromContacts)
    {
        id recipientPhoneNumbers = dict[@"CPhones"];
        if (recipientPhoneNumbers != [NSNull null])
            [phoneNumbers addObjectsFromArray:recipientPhoneNumbers];
    }

    id recipientPhoneNumbers = _personRecepient[@"CellPhone"];
    if (recipientPhoneNumbers != [NSNull null])
        [phoneNumbers addObjectsFromArray:recipientPhoneNumbers];

    NSLog(@"%@", phoneNumbers);

    return phoneNumbers;
}

我应用了Cocoa编码约定,因此ivars现在以下划线为前缀。