NSMutableArray只包含最后一个对象的副本

NSMutableArray只包含最后一个对象的副本

问题描述:

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

//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 

原因是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 
+0

当我按照上面的代码,但我提出我的代码中创建对象的语句,它的工作,我收到一个ARC错误。谢谢! – Nate

+0

@Nate:用ARC你不需要调用'release',只是不要调用它,ARC会自动释放对象。 – Dave