代码库> 数据持久化> 从此又能和CoreData愉快的玩耍了,一个简化CoreData使用的Wrapper,支持多线程
从此又能和CoreData愉快的玩耍了,一个简化CoreData使用的Wrapper,支持多线程
关注
查看次数:2826 下载次数:9
上传时间:2014-07-01 大小:
从此又能和CoreData愉快地玩耍啦

First, prepare CoreData environment:
1. import CoreData Framework

cvpic('http://ww4.sinaimg.cn/large/578b198bgw1ehrmzr0gwzj20rb059t98.jpg','','700','700')

2. add xdatamodeld file and design your model and generate sub class file
cvpic('http://ww2.sinaimg.cn/large/578b198bgw1ehrn492fm6j20ny0bb40f.jpg','','700','700')

generate sub class in Editor > Create NSManagedContext SubClass
3. copy files to your project
4. init instance in appDelegate
[pre]- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    [[mmDAO instance] setupEnvModel:@"asyncCoreDataWrapper" DbFile:@"asyncCoreDataWrapper.sqlite"];    return YES;}- (void)applicationWillTerminate:(UIApplication *)application{    // Saves changes in the application's managed object context before the application terminates.    [self saveContext];}- (void)saveContext{    NSError *error = nil;    if ([[mmDAO instance].bgObjectContext hasChanges]) {        [[mmDAO instance].bgObjectContext save:&error];    }}[/pre]
5. import catalog class in Prefix.pch file than you can use it anywhere
[pre]#import #ifndef __IPHONE_3_0#warning "This project uses features only available in iOS SDK 3.0 and later."#endif#ifdef __OBJC__    #import     #import     #import     #import "NSManagedObject+helper.h"#endif[/pre]
How to use
Create new object
[pre]Entity *task = [Entity createNew];task.task_id = @([self genId]);task.title = _txInputBox.text;task.detail = @"[not sure]";task.done = NO;[/pre]
Delete object
[pre]Entity *task = _dataArray[indexPath.row];[Entity delobject:task];[/pre]
Save Changes
[pre][Entity save:^(NSError *error) {    _txInputBox.text = @"";    [self fetchEntitys];}];[/pre]
Fetch Data Array
sync way:
[pre]NSArray *results = [Entity filter:@"task_id>10" orderby:@[@"task_id"] offset:0 limit:0];[/pre]
async way:
[pre][Entity filter:nil orderby:@[@"task_id"] offset:0 limit:0 on:^(NSArray *result, NSError *error) {    _dataArray = result;    [_mainTable reloadData]; //reload table view}];[/pre]Do complex operation asynchronously
[pre][Entity async:^id(NSManagedObjectContext *ctx, NSString *className) {        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:className];        [request setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"task_id" ascending:YES]]];        NSError *error;        NSArray *dataArray = [ctx executeFetchRequest:request error:&error];        if (error) {            return error;        }else{            return dataArray;        }    } result:^(NSArray *result, NSError *error) {        _dataArray = result;        [_mainTable reloadData];    }];
[/pre]
收藏
我来说两句
发表评论
您还没有登录!请登录注册
所有评论(0
提示
sina weixin mail 回到顶部