MagicalRecord使用中的注意事项
将bundle中的CoreData相关文件复制到沙盒目录中并使用
复制这三个文件
然后用单例初始化
//
// GlobalCoreData.h
// YXMWeather
//
// Created by XianMingYou on 15/2/20.
// Copyright (c) 2015年 XianMingYou. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "CityCode.h"
@interface GlobalCoreData : NSObject
+ (void)globalInit;
@end
//
// GlobalCoreData.m
// YXMWeather
//
// Created by XianMingYou on 15/2/20.
// Copyright (c) 2015年 XianMingYou. All rights reserved.
//
#import "GlobalCoreData.h"
@implementation GlobalCoreData
+ (void)globalInit {
GCDGroup *group = [GCDGroup new];
if ([@"/Documents/CityCode.sqlite" exist] == NO) {
[[GCDQueue globalQueue] execute:^{
NSString *srcPath = [@"CityCode.sqlite" bundleFile];
NSString *dstPath = [@"/Documents/CityCode.sqlite" path];
[[NSFileManager defaultManager] copyItemAtPath:srcPath
toPath:dstPath
error:nil];
} inGroup:group];
}
if ([@"/Documents/CityCode.sqlite-shm" exist] == NO) {
[[GCDQueue globalQueue] execute:^{
NSString *srcPath = [@"CityCode.sqlite-shm" bundleFile];
NSString *dstPath = [@"/Documents/CityCode.sqlite-shm" path];
[[NSFileManager defaultManager] copyItemAtPath:srcPath
toPath:dstPath
error:nil];
} inGroup:group];
}
if ([@"/Documents/CityCode.sqlite-wal" exist] == NO) {
[[GCDQueue globalQueue] execute:^{
NSString *srcPath = [@"CityCode.sqlite-wal" bundleFile];
NSString *dstPath = [@"/Documents/CityCode.sqlite-wal" path];
[[NSFileManager defaultManager] copyItemAtPath:srcPath
toPath:dstPath
error:nil];
} inGroup:group];
}
[[GCDQueue globalQueue] notify:^{
[MagicalRecord setupCoreDataStackWithStoreAtURL:[NSURL fileURLWithPath:[@"/Documents/CityCode.sqlite" path]]];
} inGroup:group];
}
@end
此处要记得设置初始化路径.
[MagicalRecord setupCoreDataStackWithStoreAtURL:[NSURL fileURLWithPath:[@"/Documents/CityCode.sqlite" path]]];
关于NSManagedObjectContext的一些使用细节
NSManagedObjectContext保存了操作数据库句柄的一些上下文,在MagicalRecord中,我们有时候会在子线程中进行查询操作,而到主线程中进行显示操作.问题来了,在实际使用过程中,操作句柄对象NSManagedObjectContext会在跨线程的过程中丢失掉,也就是说数据变成空了.
这个时候,我们需要将操作句柄NSManagedObjectContext定义成属性,然后用
[NSManagedObjectContext MR_context]
来获取出操作句柄并作为属性存储起来(防止丢失)
然后,你就可以做你自己想做的炒作了;)
比如以下操作:
[GCDQueue executeInGlobalQueue:^{
NSPredicate *searchInfo = [NSPredicate predicateWithFormat:@"%@ IN [cd] cityName", textField.text];
self.magicArray = [CityCode MR_findAllWithPredicate:searchInfo
inContext:self.context];
[GCDQueue executeInMainQueue:^{
[self.tableView reloadData];
}];
}];