您的位置:首页 > 其它

使用coreData

2016-04-12 14:34 295 查看
1、设计数据模型



2、创建持久化视图和控制器

#import "BIDViewController.h"
#import "BIDAppDelegate.h"

static NSString * const kLineEntityName = @"Line";
static NSString * const kLineNumberKey = @"lineNumber";
static NSString * const kLineTextKey = @"lineText";

@interface BIDViewController ()

@property (strong, nonatomic) IBOutletCollection(UITextField) NSArray *lineFields;

@end

@implementation BIDViewController

- (void)viewDidLoad
{
[super viewDidLoad];
    //获取应用委托的引用,使用引用获得创建托管对象上下文。
BIDAppDelegate * appDelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext * context = [appDelegate managedObjectContext];

    //创建一个获取请求并将实体描述传递给它,以便请求知道要检索的对象类型。
NSFetchRequest * request = [[NSFetchRequest alloc]
initWithEntityName:kLineEntityName];

//通过执行没有谓语的请求,上下文将返回库中的每一个Line对象。
NSError * error;
NSArray * objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
NSLog(@"There was an error!");
// Do whatever error handling is appropriate
}

    //遍历以获取托管对象数组,从中提取每个托管对象的lineNumber和lineText值,并使用信息更新界面的文本框。
for (NSManagedObject * oneObject in objects) {
int lineNum = [[oneObject valueForKey:kLineNumberKey] intValue];
NSString *lineText = [oneObject valueForKey:kLineTextKey];

UITextField *theField = self.lineFields[lineNum];
theField.text = lineText;
}

UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:app];
}

- (void)applicationWillResignActive:(NSNotification *)notification
{
    //先获取对应的委托引用,然后使用此引用获取指向应用的默认上下文指针。
BIDAppDelegate * appDelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext * context = [appDelegate managedObjectContext];
NSError *error;
for (int i = 0; i < 4; i++) {
UITextField *theField = self.lineFields[i];
       //为line实体创建获取请求,创建一个谓语,确认持久存储中是否已经有一个与这个字段对应的托管对象。
NSFetchRequest *request = [[NSFetchRequest alloc]
initWithEntityName:kLineEntityName];
NSPredicate *pred = [NSPredicate
predicateWithFormat:@"(%K = %d)", kLineNumberKey, i];
[request setPredicate:pred];
//在上下文中执行获取请求
NSArray * objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
NSLog(@"There was an error!");
// Do whatever error handling is appropriate
}

//申明一个指向NSManagedObject的指针并将它设置为nil。检查返回值对象objects,如果存在有效对象就加载,否则创建一个新的托管对象来保存这个字段的文本。
NSManagedObject * theLine = nil;
if ([objects count] > 0) {
theLine = [objects objectAtIndex:0];
} else {
theLine = [NSEntityDescription
insertNewObjectForEntityForName:kLineEntityName
inManagedObjectContext:context];
}
//使用键——值编码来设置行号以及此托管对象的文本。
[theLine setValue:[NSNumber numberWithInt:i] forKey:kLineNumberKey];
[theLine setValue:theField.text forKey:kLineTextKey];
}
    //通知上下文保存修改。
[appDelegate saveContext];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: