簡體   English   中英

從nsdictionary中刪除鍵/值

[英]Remove keys/values from nsdictionary

我正在嘗試將我的coredata轉換為json,我一直在努力讓這個工作,但已找到一種幾乎正常工作的方式。

我的代碼:

NSArray *keys = [[[self.form entity] attributesByName] allKeys];
        NSDictionary *dict = [self.form dictionaryWithValuesForKeys:keys];
        NSLog(@"dict::%@",dict);

        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                           options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                             error:&error];

        if (! jsonData) {
            NSLog(@"Got an error: %@", error);
        } else {
            NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSLog(@"json::%@",jsonString);
        }

“形式”也是:

 @property (strong, retain) NSManagedObject *form;

除了我在某些coredata屬性中保存了NSIndexSet之外,這個工作正常。 這給JSON寫入帶來了問題。 現在,我的索引集不需要轉換為json所以我想知道是否有辦法從dict中刪除所有索引? 或者有更好的方法來做到這一點,我不知道。

這是dlog的nslog的一部分:

...
    whereExtent = "";
    wiring =     (
    );
    wiring1 = "<NSIndexSet: 0x82b0600>(no indexes)";
    wiringUpdated = "<null>";
    yardFenceTrees = "<null>";
}

所以在這種情況下我想從dict中刪除“wiring1”但需要能夠以“動態”的方式進行(不使用名稱“wiring1”來刪除它)

為了能夠刪除值,您的字典必須是NSMutableDictionary類的實例。

要動態刪除值,從dict獲取所有鍵,測試每個鍵的對象並刪除不必要的對象:

NSArray *keys = [dict allKeys];
for (int i = 0 ; i < [keys count]; i++)
 {
   if ([dict[keys[i]] isKindOfClass:[NSIndexSet class]])
   {
     [dict removeObjectForKey:keys[i]];
   }
}

注意:刪除值不適用於快速枚舉。 作為替代快速黑客,您可以創建一個沒有不必要對象的新字典。

使用NSMutableDictionary而不是NSDictionary.Your代碼將如下所示:

NSMutableDictionary *dict = [[self.form dictionaryWithValuesForKeys:keys] mutableCopy]; //create dict
[dict removeObjectForKey:@"wiring1"]; //remove object

不要忘記使用mutableCopy。

此示例代碼將通過NSDictionary並構建一個僅包含JSON安全屬性的新NSMutableDictionary

目前它不能遞歸地工作,例如,如果你的字典包含字典或數組,它將刪除它而不是通過字典本身並修復它,但這很簡單,可以添加。

// Note: does not work recursively, e.g. if the dictionary contains an array or dictionary it will be dropped.
NSArray *allowableClasses = @[[NSString class], [NSNumber class], [NSDate class], [NSNull class]];
NSDictionary *properties = @{@"a":@"hello",@"B":[[NSIndexSet alloc] init]};
NSMutableDictionary *safeProperties = [[NSMutableDictionary alloc] init];

[properties enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
    BOOL allowable = NO;
    for (Class allowableClass in allowableClasses)          {
        if ([obj isKindOfClass:allowableClass])
        {
            allowable = YES;
            break;
        }
    }       
    if (allowable)
    {
        safeProperties[key] = obj;
    }
}];
NSLog(@"unsafe: %@, safe: %@",properties,safeProperties);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM