码迷,mamicode.com
首页 > 其他好文 > 详细

Core Data使用

时间:2015-07-17 18:41:49      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

注意:每次修改CoreData的Attribute时记得把应用给删除重装,要不会崩,因为建立的数据库文件还在该目录下,里面的字段没有更改,所以不能匹配就会崩溃,切忌,要不就每次进来把文件先删除,再建立,不过貌似这样做用户的数据就会丢失,所以还是每次删除应用再装吧。??

1.先建立一个coredata的工程,把Use Core Data勾上

进去后的AppDelegate.m中有如下代码:

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

//存储在沙盒里的具体位置
- (NSURL *)applicationDocumentsDirectory { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.pupuwang.XWClient.CoreDataDemo" in the application‘s documents directory. return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; }
//托管对象
- (NSManagedObjectModel *)managedObjectModel { // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model. if (_managedObjectModel != nil) { return _managedObjectModel; } NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CoreDataDemo" withExtension:@"momd"]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return _managedObjectModel; }
//持久化存储协调器
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. if (_persistentStoreCoordinator != nil) { return _persistentStoreCoordinator; } // Create the coordinator and store _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataDemo.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]) { // Report any error we got. 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]; // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _persistentStoreCoordinator; } //托管上下文 - (NSManagedObjectContext *)managedObjectContext { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) if (_managedObjectContext != nil) { return _managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (!coordinator) { return nil; } _managedObjectContext = [[NSManagedObjectContext alloc] init]; [_managedObjectContext setPersistentStoreCoordinator:coordinator]; return _managedObjectContext; } #pragma mark - Core Data Saving support - (void)saveContext { NSManagedObjectContext *managedObjectContext = self.managedObjectContext; if (managedObjectContext != nil) { NSError *error = nil; if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } } }

自己手动建立起来coredata文件,也可以自己手动写

2.建立实体

选中xcdatamodeld后缀文件,按下面步骤操作:

技术分享

选中xcdatamodeld后缀文件,点击导航栏Editor->Create NSManagedObject Subclass 一路next,建立模型对象User.h User.m

其中生成的model:User里面的属性用的是@dynamic

@property有两个对应的词,一个是@synthesize,一个是@dynamic。如果@synthesize和@dynamic都没写,那么默认的就是@syntheszie var = _var;

 

@synthesize的语义是如果你没有手动实现setter方法和getter方法,那么编译器会自动为你加上这两个方法。

@dynamic告诉编译器,属性的setter与getter方法由用户自己实现,不自动生成。(当然对于readonly的属性只需提供getter即可)。假如一个属性被声明为@dynamic var,然后你没有提供@setter方法和@getter方法,编译的时候没问题,但是当程序运行到instance.var =someVar,由于缺setter方法会导致程序崩溃;或者当运行到 someVar = var时,由于缺getter方法同样会导致崩溃。编译时没问题,运行时才执行相应的方法,这就是所谓的动态绑定。

3.APPDelegate.m中

_window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
View1Controller *view1 = [[View1Controller alloc]init];
view1.myAppdelegate = self;
_window.rootViewController = view1;
[_window makeKeyAndVisible];

 

4.View1Controller.h中

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#import "AppDelegate.h"
#import "User.h"

@interface View1Controller : UIViewController
@property (nonatomic,strong) AppDelegate *myAppdelegate;//创建该视图的记得把值传过来
@end

5.View1Controller.m中

#import "View1Controller.h"

@interface View1Controller ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *ageTF;
@property (weak, nonatomic) IBOutlet UITextField *sexTF;
@property (weak, nonatomic) IBOutlet UITextView *serchContent;


@end

@implementation View1Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // Do any additional setup after loading the view, typically from a nib.
}

#pragma mark - Click
//保存数据
- (IBAction)saveData:(id)sender {
    User *user = (User *)[NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.myAppdelegate.managedObjectContext];
    [user setName:self.nameTF.text];
    [user setAge:@([self.ageTF.text integerValue])];
    [user setSex:self.sexTF.text];
    [user setBirth:[NSDate dateWithTimeIntervalSinceNow:100000]];
    [self saveStatus];
}
//查询数据
- (IBAction)serchData:(id)sender { NSFetchRequest *request = [[NSFetchRequest alloc]init]; NSEntityDescription *user = [NSEntityDescription entityForName:@"User" inManagedObjectContext:self.myAppdelegate.managedObjectContext]; [request setEntity:user]; NSError *error; NSArray *mutablefetchResult = [self.myAppdelegate.managedObjectContext executeFetchRequest:request error:&error]; if (mutablefetchResult == nil) { NSLog(@"Seach fail"); } NSLog(@"coredata entity count is %ld",[mutablefetchResult count]); NSMutableString *string = [[NSMutableString alloc]init]; for (User *user in mutablefetchResult) { [string appendFormat:@"name = %@,age = %@,sex = %@,birthDay = %@",user.name,user.age,user.sex,user.birth]; [string appendFormat:@"\n"]; } self.serchContent.text = string; } //更新数据 - (IBAction)updateData:(id)sender { NSFetchRequest *request =[[NSFetchRequest alloc]init]; NSEntityDescription *user = [NSEntityDescription entityForName:@"User" inManagedObjectContext:self.myAppdelegate.managedObjectContext]; [request setEntity:user]; NSError *error; //设置查询条件 NSPredicate (谓词):查询语句 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",self.nameTF.text]; [request setPredicate:predicate]; NSArray *mutabelFetchResult = [self.myAppdelegate.managedObjectContext executeFetchRequest:request error:&error]; if (mutabelFetchResult == nil) { NSLog(@"seach fail"); } NSLog(@"coredata entity count is %ld",mutabelFetchResult.count); for (User *user in mutabelFetchResult) { [user setAge:@([self.ageTF.text integerValue])]; } [self saveStatus]; }
//删除数据
- (IBAction)cancelData:(id)sender { NSFetchRequest *request = [[NSFetchRequest alloc]init]; NSEntityDescription *user = [NSEntityDescription entityForName:@"User" inManagedObjectContext:self.myAppdelegate.managedObjectContext]; [request setEntity:user]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",self.nameTF.text]; [request setPredicate:predicate]; NSError *error; NSArray *mutableFetchResult = [self.myAppdelegate.managedObjectContext executeFetchRequest:request error:&error]; if (mutableFetchResult == nil) { NSLog(@"search fail"); } NSLog(@"coredata entity count is %ld",mutableFetchResult.count); for (User *user in mutableFetchResult) { [self.myAppdelegate.managedObjectContext deleteObject:user]; } [self saveStatus]; } //数据是否保存成功 - (void)saveStatus{ NSError *error; BOOL isSuccess = [self.myAppdelegate.managedObjectContext save:&error]; if (!isSuccess) { NSLog(@"save fail"); }else{ NSLog(@"save success"); } } -(BOOL)textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; return YES; }

 

Core Data使用

标签:

原文地址:http://www.cnblogs.com/yyzanll/p/4655187.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!