2 starwar2012 starwar2012 于 2013.01.15 10:52 提问

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;
 }

如何实现?

1个回答

langyufei
langyufei   2013.01.16 13:48
已采纳

两个办法,简单直观的就是利用已有的不可变的数组或者字典创建可变的(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"];
}
Csdn user default icon
上传中...
上传图片
插入图片