我正在编写一个 GPS 运行应用程序,我想为每个“路径”或运行存储多个位置。 我在理解 ORM 风格数据库的新概念时遇到了一些困难。 (我知道 Core Data 使用 SQLLite 作为底层机制,并不是真正的 ORM,但除此之外......) 我设置了两个实体,“路径”和“位置”,具有从“路径>>位置”进行级联删除的“多对多”关系,以及一个仅具有删除无效的逆关系。
我正在做:
//SEND TO CORE DATA
bdAppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
// get GPS lat/lng
double lat = newLocation.coordinate.latitude;
double lng = newLocation.coordinate.longitude;
// insert Path
Path *currentPathInfo = [NSEntityDescription insertNewObjectForEntityForName:@"Path" inManagedObjectContext:context];
currentPathInfo.name = currentPathName;
currentPathInfo.createddate =[NSDate date];
// insert location/GPS point
Location *currentPathLocation = [NSEntityDescription insertNewObjectForEntityForName:@"Location" inManagedObjectContext:context];
currentPathLocation.lat = [NSNumber numberWithDouble:lat];
currentPathLocation.lng = [NSNumber numberWithDouble:lng];
// insert 'Location' relationship to 'Path'
[currentPathInfo addLocationsObject:currentPathLocation];
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
这是在初始启动时(按下按钮) 但是,我如何继续添加更多与初始“路径”相关的“位置”,而不是由于重复上述代码而继续添加更多“路径”?
在 SQL 中,我有一个 PathID 整数(身份),我将其用作“位置”表中的外键来插入位置...我正在断开连接...
最佳答案
建立关系只有两种方式:
[currentPathInfo addLocationsObject:currentPathLocation];
或
currentPathLocation.path = currentPathInfo;
因此,您需要在某处使用 ivar 记住您的“currentPathInfo”,或者每次根据某种唯一标识符(如果有的话)从核心数据中获取它。
关于iOS 核心数据 : How do I add subsequent records to the 'many' of 1:many relationships?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19128831/