数据存储之CoreData

时间:2025-01-09 15:05:08

#import "ViewController.h"

#import <CoreData/CoreData.h>

#import "Person.h"

@interface ViewController ()

@end

@implementation ViewController

{

NSManagedObjectContext *_context;

}

- (void)viewDidLoad {

[super viewDidLoad];

//获取上下文

_context = [[NSManagedObjectContext alloc]init];

//添加model

NSManagedObjectModel *model = [NSManagedObjectModel mergedModelFromBundles:nil];

NSPersistentStoreCoordinator *store = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];

NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];

NSString *sqlitePath = [doc stringByAppendingString:@"/person.sqlite"];

// NSString *sqlitePath = [doc stringByAppendingPathExtension:@"person.sqlite"];

NSLog(@"%@",sqlitePath);

NSError *error = nil;

[store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:sqlitePath] options:nil error:&error];

_context.persistentStoreCoordinator = store;

[self addPerson];

[self findPerson];

}

- (void)addPerson{

//创建对象

Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_context];

person.name = @"hzt";

person.age = @"15";

person.phone = @"1314";

//保存数据

NSError *error = nil;

if ([_context save:&error]){

NSLog(@"保存成功");

}else{

NSLog(@"保存失败");

}

}

- (void)findPerson{

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",@"hzt"];

request.predicate = predicate;

NSError *error = nil;

NSArray *array = [_context executeFetchRequest:request error:&error];

for (Person *per in array){

NSLog(@"%@,%@",per.name,per.age);

}

}

------------------参考文献-------------------------------

http://www.jianshu.com/p/8299b7360dd6