NSMutableArray只有最后一个对象的副本

时间:2012-11-19 20:46:29

标签: ios xcode nsmutablearray nsxml

我使用NSXML解析XML文档并将结果添加到对象数组中。数组具有正确数量的对象,但它们充满了来自最后一个对象的数据(即索引0处的对象具有与索引3处相同的数据)。我从服务器上获得了良好的数据。

//set up my objects and arrays higher in my structure
SignatureResult *currentSignatureResult = [[SignatureResult alloc]init];
Document *currentDoc = [[Document alloc]init];
Role *currentRole = [[Role alloc]init];             
NSMutableArray *roleArray = [[NSMutableArray alloc] init];
NSMutableArray *doclistArray2 = [[NSMutableArray alloc] init];


.....there is more parsing up here
//role is defined as an NSXML Element
for (role in [roleList childrenNamed:@"role"]){

    NSString *firstName =[role valueWithPath:@"firstName"];
    NSString *lastName = [role valueWithPath:@"lastName"];
    currentRole.name = [NSString stringWithFormat:@"%@ %@",firstName, lastName];



    for (documentList2 in [role childrenNamed:@"documentList"])
       {
        SMXMLElement *document = [documentList2 childNamed:@"document"];
        currentDoc.name = [document attributeNamed:@"name"];
        [doclistArray2 addObject:currentDoc];
        }
    currentRole.documentList = doclistArray2;
    [roleArray addObject:currentRole];
    ///I've logged currentRole.name here and it shows the right information

}//end of second for statemnt

currentSignatureResult.roleList = roleArray;
}
///when I log my array here, it has the correct number of objects, but each is full of
///data from the last object I parsed

1 个答案:

答案 0 :(得分:2)

原因是addObjects:保留了currentRole对象而没有从中创建副本。您可以在for内创建新的currentRole对象,也可以从中创建副本并将其添加到数组中。 我推荐以下内容:

for (role in [roleList childrenNamed:@"role"]){
    Role *currentRole = [[Role alloc] init];
    NSString *firstName =[role valueWithPath:@"firstName"];
    NSString *lastName = [role valueWithPath:@"lastName"];
    currentRole.name = [NSString stringWithFormat:@"%@ %@",firstName, lastName];



    for (documentList2 in [role childrenNamed:@"documentList"])
       {
        SMXMLElement *document = [documentList2 childNamed:@"document"];
        currentDoc.name = [document attributeNamed:@"name"];
        [doclistArray2 addObject:currentDoc];
        }
    currentRole.documentList = doclistArray2;
    [roleArray addObject:currentRole];
    ///I've logged currentRole.name here and it shows the right information
    [currentRole release];

}//end of second for statemnt