程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> objective c-objectiveC中創建NSMutableArray

objective c-objectiveC中創建NSMutableArray

編輯:編程綜合問答
objectiveC中創建NSMutableArray

有一個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"];
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved