根据ID Objective-C

时间:2017-07-18 03:47:47

标签: ios objective-c nspredicate

我有以下shared.orderItems。我正在使用sharedData.orderITems id shared.comboItem用于构建sharedData.orderItems。我想知道如何在没有comboItemId等于id的情况下过滤id数据。

例如,在以下示例中,71中使用了72 shared.ComboItems71两个项目。我想在72上过滤shared.orderItems1,并且只保留对象ID (lldb) po sharedData.orderItems <__NSArrayM 0x174050860>( { Note = ""; Quantity = 1; id = 72; }, { Note = ""; Quantity = 1; id = 71; }, { Note = ""; Quantity = 2; id = 1; } ) (lldb) po sharedData.comboItems <__NSArrayM 0x174247620>( { Note = ""; Quantity = 1; comboItemId = 72; id = 3; }, { Note = ""; Quantity = 1; comboItemId = 71; id = 19; }, { Note = ""; Quantity = 1; comboItemId = 72; id = 20; }, { Note = ""; Quantity = 1; comboItemId = 72; id = 21; } )

from tkinter import *
from time import sleep
root = Tk()
l1 = Label(root, text="Ok")
l1.pack()
sleep(5)
l2 = Label(root, text="Great")
l2.pack()
sleep(10)
l3 = Label(root, text="Nice")
l3.pack()
root.mainloop()

3 个答案:

答案 0 :(得分:4)

我认为我理解这个问题意味着要排除orderItems数组中comboItemId属性引用的comboItems。首先收集那些:

NSMutableSet *excludedIds = [NSMutableSet set];
for (NSDictionary *item in sharedData.comboItems) {
    [excludedIds addObject:item[@"comboItemId"]]; // EDIT
}

可以通过谓词过滤数组,并且可以使用格式字符串(see here)指定这些数组。所以你需要:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (id IN %@)", excludedIds];
NSArray *filtered = [sharedData.orderItems filteredArrayUsingPredicate:predicate];

答案 1 :(得分:2)

你试过谓词吗?

  1. 过滤shared.comboItems以将所有comboItemId放入数组。
  2. 将谓词与NOT IN一起使用以过滤sharedData.orderItems
  3. <强>解决方案:

    NSArray *unique = [shared.comboItems valueForKeyPath:@"@distinctUnionOfObjects.comboItemId"];
    NSPredicate *nonePredicate = [NSPredicate predicateWithFormat: @"NOT(id IN %@)", unique];
    NSArray *filtered = [sharedData.orderItems filteredArrayUsingPredicate:nonePredicate];
    NSLog(@"Filtered: %@", filtered);
    

答案 2 :(得分:2)

您可以使用键值编码 - 收集运算符从组合项中获取ids

@distinctUnionOfObjects:返回运算符右侧键路径中指定的属性中的对象数组

NSArray *compoIds = [sharedData.CompoItems valueForKeyPath:@"@distinctUnionOfObjects.comboItemId"];

NSPredicate *dupIdsPredicate = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind) {
     NSDictionary *orderItemDictionary = (NSDictionary *) obj;
     return  ![compoIds containsObject:[orderItemDictionary valueForKey:@"id"]];
}];

NSArray *unionOfIDs =  [sharedData.orderItems filteredArrayUsingPredicate:dupIdsPredicate];

NSLog(@"%@", unionOfIDs);