2012-11-19 110 views
1

我正在使用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 

回答

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 
+0

當我按照上面的代碼,但我提出我的代碼中創建對象的語句,它的工作,我收到一個ARC錯誤。謝謝! – Nate

+0

@Nate:用ARC你不需要調用'release',只是不要調用它,ARC會自動釋放對象。 – Dave

相關問題