gpt4 book ai didi

ios - NSManagedObject 只保存最新的对象而不是整个对象

转载 作者:行者123 更新时间:2023-11-29 13:11:31 24 4
gpt4 key购买 nike

我有一个 json 响应,我正在尝试使用 NSManagedObject 和以下代码保存到核心数据:

- (void)breakTrapsToSave:(NSDictionary*)trapsDict
{
tempA = [trapsDict objectForKey:@"Envelope"];
tempB = [tempA objectForKey:@"Body"];
tempC = [tempB objectForKey:@"getTrapsResponse"];
tempD = [tempC objectForKey:@"getTrapsResult"];
tempE = [tempD objectForKey:@"TRAPS"];

self.lastUpdate = [tempE objectForKey:@"lastUpdate"];
[self.sharedPrefs setObject:self.lastUpdate forKey:@"last_update"];
[self.sharedPrefs synchronize];
NSLog(@"Traps latest updated at: %@", self.lastUpdate);

tempF = [tempE objectForKey:@"TRAP"];

[tempF enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
tempA = [tempF objectAtIndex:idx];
NSString *finalResult;
NSString *key;

for (int i=0; i < node.count; i++) {
tempB = [tempA objectForKey:[node objectAtIndex:i]];
finalResult = (NSString*)tempB;
key = [node objectAtIndex:i];

[self addToCoreData_value:finalResult key:key]; // Core Data
}
counter = idx;
}];

NSLog(@"Total Traps: %d", counter);
}

#pragma mark - Core Data Methods

- (void)initCoreData
{
IDANAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
context = appDelegate.managedObjectContext;
entityDesc = [NSEntityDescription entityForName:@"Trap" inManagedObjectContext:context];
managedObject = [[NSManagedObject alloc] initWithEntity:entityDesc insertIntoManagedObjectContext:context];
}

- (void)addToCoreData_value:(NSString*)value key:(NSString*)key
{
if ([key isEqualToString:@"alarmDistance"] ||
[key isEqualToString:@"degrees"] ||
[key isEqualToString:@"id"] ||
[key isEqualToString:@"polys"] ||
[key isEqualToString:@"roadNumber"] ||
[key isEqualToString:@"type"]) {

[managedObject setValue:[NSNumber numberWithInt:[value intValue]] forKey:key];
}
else if ([key isEqualToString:@"lat"] ||
[key isEqualToString:@"lon"]) {
[managedObject setValue:[NSNumber numberWithFloat:[value floatValue]] forKey:key];
}
else if ([key isEqualToString:@"isActive"]) {
BOOL toSet = false;

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

[managedObject setValue:[NSNumber numberWithBool:toSet] forKey:key];
}
else {
[managedObject setValue:value forKey:key];
}


NSError *error;
[context save:&error];
}

事情是,我做了日志,我看到我通过整个 enumerateObjectsUsingBlock 循环获得了正确的值和键。此外,在:

 - (void)addToCoreData_value:(NSString*)value key:(NSString*)key

我做了一个日志,我看到我也得到了所有的键和值。但是当我打开 sqlite 时,我只看到表中的一行,即最后一个对象。NSLog(@"Total Traps: %d", counter); - 还打印正确数量的对象(目前为 116 个)。

我做错了什么?

最佳答案

看起来您只有一个托管对象。您所做的只是连续更改它的属性。

您应该做的是为您保存的每个项目创建一个新的托管对象。

关于ios - NSManagedObject 只保存最新的对象而不是整个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17251741/

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