【问题标题】:Coredata find one array contain valuesCoredata 找到一个包含值的数组
【发布时间】:2017-09-16 19:22:00
【问题描述】:

我有一个核心数据表,它包含 100 个数据和一个可变数组有一些数据。 iw ant 搜索包含数据的可变数组是否存在于表中。可变数组包含 3 个使用这些参数的参数我需要找出一个包含我表的 id 我正在使用此代码

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ IN self.@allKeys" ,self.beaconListArray ];
request.predicate = predicate;
NSError *error = nil;
NSArray *objs = [managedObjectContext executeFetchRequest:request error:&error];
if (error) {
    [NSException raise:@"no  find" format:@"%@", [error localizedDescription]];
    NSLog(@"there is noooo  with same id exsist");
}
if (objs.count > 0) {
    NSLog(@"there is a with same id exsist. Use update method");
}else {
    NSLog(@"there's no  with same id. Use insert method");
}

【问题讨论】:

    标签: ios objective-c xcode core-data nspredicate


    【解决方案1】:

    据我了解,您有一组数据。每个数据项都是字典或自定义对象或其他东西,并且有一个 uniqueId。您想要将数据插入或更新到核心数据中。

    我不确定您为 uniqueId 使用的属性或您尝试插入的数据类型。所以这段代码只是为了演示。

    首先从数据中获取 uniqueIds。比如:

    NSArray* thingIdArray = [self.beaconListArray valueForKeyPath:@"uuid"];
    

    接下来进行抓取。您的谓词可能类似于

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K IN %@", @"uuid", thingIdArray];
    

    下一步将托管对象数组的结果转换为字典,其中键是 uniqueId。

    NSMutableDictionary* dict = [NSMutableDictionary dictionary];
    for (CoreDataThing* t in result) {
        NSString* thingId = t.uuid;
        if (thingId) {
            dict[thingId] = t;
        }
    }
    

    现在您可以查看每个数据项是否已存在

    for (NSDictionary* a in self.beaconListArray) {
        NSString* thingId = a[@"uuid"];
        CoreDataThing* coreDataThing = dict[thingId];
        if (!coreDataThing) {
             coreDataThing = //create it here and set default values
        }
        [coreDataThing updateWithSomeObject:a]
    }
    

    【讨论】:

    • 我有一个可变数组 { major = 1;次要 = 4541; uuid = "xxxxxxxx"; }, { 主要 = 1;次要 = 6000; uuid = "xxxxxxx"; },使用这些数据我想在 coredata 数据表中搜索并找出相应的 id。使用该 id 我需要在我的视图中显示一些东西。如何获得这些
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    相关资源
    最近更新 更多