2012-11-24 68 views
1

我有以下字典,它有許多子字典。 如何使用NSPredicate從父字典中刪除對象isChanged = 1使用NSPredicate刪除對象

{ 
    "0_496447097042228" =  { 
     cellHeight = 437; 
     isChanged = 1; 
    }; 
    "100000019882803_193629104095337" =  { 
     cellHeight = 145; 
     isChanged = 0; 
    }; 
    "100002140902243_561833243831980" =  { 
     cellHeight = 114; 
     isChanged = 1; 
    }; 
    "100004324964792_129813607172804" =  { 
     cellHeight = 112; 
     isChanged = 0; 
    }; 
    "100004324964792_129818217172343" =  { 
     cellHeight = 127; 
     isChanged = 0; 
    }; 
    "100004324964792_129835247170640" =  { 
     cellHeight = 127; 
     isChanged = 1; 
    }; 
} 
+0

您的問題發生什麼..? – Rajneesh071

+0

我用@J夏皮羅的回答 – Shamsiddin

+0

確定兄弟然後接受他的答案和+1,我的代碼也可以工作,如果你有這種格式的數據 – Rajneesh071

回答

2

我解決了我以下列方式問題:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isChanged == %d", 1]; 

NSArray *allObjs = [parentDict.allValues filteredArrayUsingPredicate:predicate]; 

[allObjs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
    NSMutableArray *keys = [[NSMutableArray alloc] initWithCapacity:0]; 
    [keys setArray:[parentDict allKeysForObject:obj]]; 
    [parentDict removeObjectsForKeys:keys]; 
    [keys release]; 
}]; 
0

比你可以刪除選擇使用NSPredicate

此類別的數據,當你有字典的數組代碼

NSString *selectedCategory = @"1"; 

//filter array by category using predicate 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"isChanged == %@", selectedCategory]; 

NSArray *filteredArray = [yourAry filteredArrayUsingPredicate:predicate]; 

[yourAry removeObject:[filteredArray objectAtIndex:0]]; 

但你的問題的數據是不是在陣列它在字典

您的數據應該採用此格式

(
{ 
    cellHeight = 437; 
    isChanged = 1; 
}, 
{ 
    cellHeight = 145; 
    isChanged = 0; 
}, 
{ 
    cellHeight = 114; 
    isChanged = 1; 
} 
) 
3

作爲一個簡單的替代使用NSPredicate,您可以使用內置的keysOfEntriesPassingTest:這個答案假定「isChanged」中的NSDictionary的是一個NSString和值爲0或1是一個NSNumber:

NSSet *theSet = [dict keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop) { 
    return [obj[@"isChanged"] isEqualToNumber: @1]; 
}]; 

返回集通過測試的密鑰列表。從那裏,你可以刪除所有與匹配:

[dict removeObjectsForKeys:[theSet allObjects]];

+0

該塊中的代碼可以簡化爲:return [obj [@「isChanged」] isEqual:@ 1];沒有必要使用if-else子句。 – rdelmar

+0

您不需要避免iOS的文字<= 5,因爲它可以向後兼容iOS4,因爲您可以在這裏看到http://developer.apple.com/library/ios/#releasenotes/ObjectiveC/ObjCAvailabilityIndex/_index.html並且您使用的基於塊的過濾方法可以從iOS4開始使用 - 因此不需要編寫兩種方法。 – Abizern

+0

爲了清晰起見,我打算留下詳細的答案,但我認爲你是對的@rdelmar,即使沒有條款也很清楚。 –