objectiveC NSMutableArray添加NS​​MutableDictionary问题

时间:2015-10-29 10:30:30

标签: objective-c

NSMutableDictionary *elementsMDic = [NSMutableDictionary new];
for (int i = 0 ; i < maxRssiMArray.count; i++) {

    NSString *majorStr = [NSString stringWithFormat:@"%@",[maxRssiMArray[i]valueForKey:@"major"]];
    NSString *minorStr = [NSString stringWithFormat:@"%@",[maxRssiMArray[i]valueForKey:@"minor"]];
    NSInteger rssiInt = [[maxRssiMArray[i] valueForKey:@"rssi"] intValue];

    [elementsMDic setValue:@"guest" forKey:@"user_name"];
    [elementsMDic setValue:majorStr forKey:@"major"];
    [elementsMDic setValue:minorStr forKey:@"minor"];
    [elementsMDic setValue:@(rssiInt) forKey:@"rssi"];
    [elementsMDic setValue:submitTime forKey:@"submit_time"];
    [elementsMDic setValue:HERE_BEACON_UUID forKey:@"beacon_uuid"];

    [maxRssiDicMArray addObject:elementsMDic];   
}
NSLog(@"%@",maxRssiDicMArray);

我得到了

{
    "beacon_uuid" = "myUUID";
    major = 65535;
    minor = 65535;
    rssi = "-95";
    "submit_time" = "2015-10-29_17:45:56";
    "user_name" = guest;
},

我的问题是为什么有些东西得到“”别人得不到“” 我认为应该是这样的

        {
    "beacon_uuid" = "myUUID";
    "major" = 65535;
    "minor" = 65535;
    "rssi" = -95;
    "submit_time" = "2015-10-29_17:45:56";
    "user_name" = "guest";
},

因为我的密钥都是NSString,而我的majorStr和minorStr都是NSString,

请告诉我为什么以及如何解决原因!!

2 个答案:

答案 0 :(得分:1)

你得到的是控制台输出,它利用了它输出的对象的description属性。根据apple docs(https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/#//apple_ref/occ/instp/NSDictionary/description),这是为了提高可读性,而不是为了对象的序列化。所以你看到的报价只是帮助你阅读它。带有空格或其他特定字符(如下划线)的字符串值用引号括起来,字符串值没有这些字符串。 您无法真正解决此问题,因为该功能正在按预期工作。既然你没有告诉我们你想要做什么,建议替代品成为猜谜游戏。如果您需要可以写入文件并稍后检索的数据,则应查看属性列表 (https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/Introduction/Introduction.html#//apple_ref/doc/uid/10000048i)  或NSArchiver(https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSArchiver_Class/index.html)。如果打算通过网络发送,NSJSONSerialization可能会满足您的需求吗? https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/

答案 1 :(得分:0)

字典是正确的,它只是NSLog

的显示行为

如果键或值仅包含字母数字字符,则不会显示双引号。

NSDictionary *dict = @{@"key" : @"value"};
NSLog(@"%@", dict);
  

{key = value; }

否则,如果键或值包含空格,下划线或其他特殊字符

NSDictionary *dict = @{@"key 1" : @"value 1"};
NSLog(@"%@", dict);

显示双引号。

  

{“key 1”=“value 1”; }

PS:不要使用valueForKey: / setValue:forKey:来获取/设置词典的值。
指定的方法是objectForKey: / setObject:forKey: