Remove objects using NSPredicate

こ雲淡風輕ζ 提交于 2019-12-18 18:30:55

问题


I have the folloving dictionary which has many sub dictionaries. How can I remove objects where isChanged = 1 from parent dictionary using 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;
    };
}

回答1:


As a simple alternative to using NSPredicate, you can use the NSDictionary's built in keysOfEntriesPassingTest: This answer assumes "isChanged" is an NSString and the value 0 or 1 is an NSNumber:

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

The returned set is a list of keys that pass the test. From there, you could remove all that matched with:

[dict removeObjectsForKeys:[theSet allObjects]];




回答2:


I solved my problem in the following way:

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



回答3:


when you have array of dictionary than you can remove selected category's data using NSPredicate

here is code

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

But in your problem data is not in array it is in dictionary

your data should be in this format

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


来源:https://stackoverflow.com/questions/13541371/remove-objects-using-nspredicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!