您的位置:首页 > 其它

CoreData的外键关联

2016-06-14 20:51 375 查看

创建工程时勾选Use Core Data自动生成以下方法

AppDelegate.h

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

//保存数据
- (void)saveContext;
//Documents路径
- (NSURL *)applicationDocumentsDirectory;

@end


AppDelegate.m

//保存上下文,保存数据
- (void)saveContext {
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
NSError *error = nil;
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}

//返回Documents的URL路径
- (NSURL *)applicationDocumentsDirectory {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.wxhl._2_CoreData______" in the application's documents directory.
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

//managedObjectModel属性的GET方法
//自动读取momd文件,创建相对应的数据模型
- (NSManagedObjectModel *)managedObjectModel {

if (_managedObjectModel != nil) {
return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"_2_CoreData______" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}

//psc属性GET方法
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}

_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Day10_02CoreData_____1_N.sqlite"];
NSError *error = nil;
NSString *failureReason = @"There was an error creating or loading the application's saved data.";
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
dict[NSLocalizedFailureReasonErrorKey] = failureReason;
dict[NSUnderlyingErrorKey] = error;
error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}

return _persistentStoreCoordinator;
}

//managedObjectContext属性的GET方法,并且设置了PSC
- (NSManagedObjectContext *)managedObjectContext {

if (_managedObjectContext != nil) {
return _managedObjectContext;
}

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (!coordinator) {
return nil;
}
_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[_managedObjectContext setPersistentStoreCoordinator:coordinator];
return _managedObjectContext;
}


1对1

AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
//通过实体描述创建第一个对象对象
Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:appDelegate.managedObjectContext];

//通过实体描述创建第一个对象对象
Dog *dog = [NSEntityDescription insertNewObjectForEntityForName:@"Dog" inManagedObjectContext:appDelegate.managedObjectContext];

//外键关联
person.dog = dog;
//保存数据
[appDelegate saveContext];


1对1数据库实现原理

/*

Person持有了Dog
在数据库文件中:
(1)ZPERSON表格中添加了ZDOG字段,与ZDOG建立外键关联
(2)ZPERSON.DOG的值 = ZDOG.Z_PK

*/


1对N

1对N数据库实现原理

AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
//创建多个对象
Dog *dog1 = [NSEntityDescription insertNewObjectForEntityForName:@"Dog" inManagedObjectContext:appDelegate.managedObjectContext];
Dog *dog2 = [NSEntityDescription insertNewObjectForEntityForName:@"Dog" inManagedObjectContext:appDelegate.managedObjectContext];
Dog *dog3 = [NSEntityDescription insertNewObjectForEntityForName:@"Dog" inManagedObjectContext:appDelegate.managedObjectContext];
//创建狗主人
Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:appDelegate.managedObjectContext];

//添加一个外键
[person addDogsObject:dog1];
//添加多个外键
[person addDogs:[NSSet setWithObjects:dog2,dog3, nil]];


1对N实现原理

/*
Person持有了多个Dog对象

Person类中多了如下一个属性
@property (nullable, nonatomic, retain) NSSet<Dog *> *dogs;

在数据库文件中:
(1)ZDOG表格中添加一个字段,Z2DOGS。
进行外键连接 ZDOG.Z2DOGS ----> ZPERSON.P_PK

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: