gpt4 book ai didi

ios - Insert multiple NSDictionary to Core Data问题

转载 作者:行者123 更新时间:2023-11-28 22:31:00 26 4
gpt4 key购买 nike

我有一个 NSArray,它包含多个 NSDictionary。我正在做的是打破 NSDictionary 并将其添加到 CoreData,但结果是每个变量(id、alarmDistance、isAlert等)将自身添加到单独的行中。我想要做的是将 NSDictionary 包含的一堆 od 对象插入同一行。

我的代码:

- (void)updateTrapsTable
{
NSArray *node = @[@"alarmDistance", @"id", @"isActive", @"lat", @"lon", @"poly0", @"poly1", @"poly2", @"polygonAzimut1", @"polygonAzimut2", @"polygonAzimut3", @"polys", @"roadNumber", @"trapDescription", @"type", @"degrees", @"direction"];

NSArray *arrayOfTraps = [[NSUserDefaults standardUserDefaults] objectForKey:@"arrayOfAllTraps"];

for (int i=0; i < arrayOfTraps.count; i++) // Enumerate all traps
{
NSMutableDictionary *singleTrap = [[NSMutableDictionary alloc] init];
singleTrap = arrayOfTraps[i];

for (int c=0; c < node.count; c++) // Enumerate all traps' attributes
{
[self addToCoreData_value:singleTrap[node[c]] key:node[c]];
}

NSLog(@"TRAP #%d ADDED TO CORE DATA!", i);
}
}

- (void)addToCoreData_value:(NSString*)value key:(NSString*)key
{
NSLog(@"Trying to add record to Core Data");

self.entity = [NSEntityDescription entityForName:@"Trap" inManagedObjectContext:self.managedObjectContext];
self.managedObject = [[NSManagedObject alloc] initWithEntity:self.entity insertIntoManagedObjectContext:self.managedObjectContext];

if ([key isEqualToString:@"id"])
{
[self.managedObject setValue:@([value integerValue]) forKey:@"trapID"];
}
else if ([key isEqualToString:@"alarmDistance"] ||
[key isEqualToString:@"degrees"] ||
[key isEqualToString:@"polys"] ||
[key isEqualToString:@"roadNumber"] ||
[key isEqualToString:@"type"])
{

[self.managedObject setValue:@([value integerValue]) forKey:key];
}
else if ([key isEqualToString:@"lat"] ||
[key isEqualToString:@"lon"])
{
[self.managedObject setValue:@([value floatValue]) forKey:key];
}
else if ([key isEqualToString:@"isActive"])
{
BOOL toSet = false;

if ([value isEqualToString:@"True"])
{
toSet = YES;
}
else
{
toSet = NO;
}

[self.managedObject setValue:@(toSet) forKey:key];
}
else
{
[self.managedObject setValue:value forKey:key];
}


NSError *error;
[self.managedObjectContext save:&error];

NSLog(@"Record added to Core Data");
}

最佳答案

您的 addToCoreData_value: 方法创建一个新的“陷阱”对象,并为每个属性调用。

您必须先更改逻辑以创建“Trap”对象,然后将所有属性添加到该对象。

关于ios - Insert multiple NSDictionary to Core Data问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17464513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com