在现有键值中添加新数组对象而无需更改-目标C

时间:2019-02-21 07:08:34

标签: ios objective-c

在我们的应用程序中,当用户首次注册时,我需要保存用户密钥及其值。所以第一次我成功创建了这种格式;

key: "ayi927GHt548"
 data: {
 userdata: [
    {classId: "001", updateDate:"2018/02/12"}
 ]}

为此,我获得了班级ID和更新日期,如下所示:这是代码

 -(void)someMethod {
   // ... do the process to get user class ID and user key
   userClassID = @"001" // string declared global
   userKey = @"ayi927GHt548" // string declared global

   [apiManager saveUserInformationwithKey:userKey andValue:[self saveCurrentUserIformationIntoUserInfoAPI]];

 }

   -(NSDictionary *)saveCurrentUserInformationIntoUserInfoAPI {

      NSDictionary *dictionaryUserInfo = @{
      @"userData": @[
          @{
              @"classId": userClassID, // I get user class id 
              @"updateDate": [self getCurrentDateTime]
           }
        ]
     };
  return dictionaryUserInfo;
}

//在全局apimanager类中,我有一种方法可以添加键值以获得最终解决方案

-(void)saveUserInformationwithKey:(NSString *)key andValue:(NSDictionary *)value {
     NSDictionary *authInform = @{
        @"key": key,
        @"value": value
     };

   // call api for post method
 }

我按照自己的意愿正确地做了很多。

但是问题是在另一种情况下,我需要将新值附加到相同的现有“ userdata”中,而无需更改前一个值,就像这样;

   key: "ayi927GHt548"
   data: {
       userdata: [
            {classId: "001", updateDate:"2019/02/18"},
            {classId: "003", updateDate:"2019/02/21"} //? here this is the new object is which i want to add
      ]
   }

我怎么能这样?请帮助

目前Iam就是这样

    NSMutableArray *dataFinal =  [NSMutableArray arrayWithObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"data"]];

    NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:5] ;
    [dict setObject:@"54455" forKey:@"classId"]; 
    [dict setObject:[self getCurrentDateTime] forKey:@"updateDate"]; 
    [dataFinal addObject:dict];
    NSLog(@"Final: %@", dataFinal);

响应看起来像这样,但是我需要在userdata里面追加

{
    key = 12345;
    data =         {
        userdata =             (
                            {
                updateDate = "2019/02/21";
                classId = 0002;
            }
        );
    };
},
    {
    updateDate = "2019/02/21";
    classId = 54455;
}

2 个答案:

答案 0 :(得分:1)

这是获取值并将其附加到数组中的方法。

NSMutableArray *userData = [dictionaryInfo objectForKey:@"userData"]; 
NSDate *yourdate = date; 
NSNumber *classID = classID; 
NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:5];
[dict setObject:classID forKey:@"classId"]; 
[dict setObject:yourdate forKey:@"updateDate"]; 
[userData addObject:dict];

我离开了我的Mac,请自己纠正语义错误。 :)

编辑: 我已将代码添加到您的userData中,请尝试添加此行并告诉我?

dataFinal = [[[[NSUserDefaults standardUserDefaults] objectForKey:@"data"] valueForKeyPath:@"data. userdata"]mutableCopy];

打印这些值,让我知道。 希望对您有帮助!

答案 1 :(得分:0)

首先,您需要获取userData数组,然后将其转换为可变的字典数组。

然后,您需要在userData中附加所需的数据,然后保存回用户默认值。