有一個NSArray給出下面的數據:
01/14/2013 13:28:06.559 IUser Reader [71164: c07] (
{
"id_acompanhante" = "";
"id_evento" = 34;
"user_id" = 1;
"inserido_por" = "Himself";
name = iUser;
status = done;
type = User;
}
{
"id_acompanhante" = 1;
"id_evento" = 34;
"user_id" = 1;
"inserido_por" = iUser;
name = "Mayara Roca";
status = naofeito;
type = companion;
}
)
想將這些數據在NSMutableArray顯示,並且給每個item.example添加另一個field。
{
"id_acompanhante" = "";
"id_evento" = 34;
"user_id" = 1;
"inserido_por" = "Himself";
name = IUser;
status = done;
type = User;
tag = 2;
}
如何實現?
兩個辦法,簡單直觀的就是利用已有的不可變的數組或者字典創建可變的(mutable)數組字典,再添加新的tag標簽.
NSArray *theOldArray; // your old array
NSMutableArray *theMutableAry = [NSMutableArray array];
for (NSDictionary *dicItem in theOldArray)
{
NSMutableDictionary *dicWithOneMoreField = [NSMutableDictionary dictionaryWithDictionary:dicItem];
[dicWithOneMoreField setValue:@"your value for tag" forKey:@"tag"];
[theMutableAry addObject:dicWithOneMoreField];
}
如果數據結構很復雜又可能變化,比如數組裡有字典,字典裡又有數組等等,那就將數據歸檔再反歸檔,這樣所有的數據就都變成mutable的了,之後隨便你怎麼操作.
NSData* archivedData = [NSKeyedArchiver archivedDataWithRootObject:theOldArray];
NSMutableArray *mutableArray = [NSKeyedUnarchiver unarchiveObjectWithData:archivedData];
for (NSDictionary *dicItem in mutableArray)
{
[dicItem setValue:@"your value for tag" forKey:@"tag"];
}