一:几种主要的存储方式
1、NSUSerDefault :这个是我们经常用的用来保存一些小数据,可以存储的类型有NSData,NSDate,NSNumber,NSString,NSDictionary,NSArray,
2、NSKeyedArchiver:这个可以用来保存对象,这个比较笨拙一般不用
3、写入文件:这个主要用来保存一些大文件 如音乐、高清图片、视屏等大数据
4、SQLite:这个主要比较常用的就是FMDB和CoreData,本人习惯用CoreData因为都是调用对象 不需要我们频繁的去写SQlite语句
二:CoreData和FMDB
1、coredata:
Managed Object Model 是描述应用程序的数据模型,这个模型包含实体(Entity),特性(Property),读取请求(Fetch Request)等。(下文都使用英文术语。)
Managed Object Context 参与对数据对象进行各种操作的全过程,并监测数据对象的变化,以提供对 undo/redo 的支持及更新绑定到数据的 UI。
Persistent Store Coordinator 相当于数据文件管理器,处理底层的对数据文件的读取与写入。一般我们无需与它打交道。
Managed Object 数据对象,与 Managed Object Context 相关联。
NSPreDicate 查询条件
NSEntityDescription实体结构
其中有关系 有一对多的和一对一的
coreData要注意线程安全问题,但是并不像习惯用FMDB的人说的那样他的线程安全问题得不到解决,苹果提供了三种方法:我最习惯用iOS 5 为NSManagedObjectContext提供的initWithConcurrentType方法,用NSPrivateQueueConcurrentcyType,会自动创建一个新线程来存放NSManagedObjectContext而且它还会自动创建NSPersistenStoreCoordinator
你在每个Viewcontroller通过这个方法得到一个NSManagedObjectContext实例 他的父亲是APPDelegate里面的那个NSManagedObjectContext,这样线程安全问题就得到解决了
关于CoreData版本升级或者增加字段 需要在 实例化 NSPersistentStoreCoordinator 它的时候加上一个可选字典
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
// Create the coordinator and store
NSDictionary *optionsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],
NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES],
NSInferMappingModelAutomaticallyOption, nil];
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CoreDataTest.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:optionsDictionary 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;
}
然后新增一个 . xcdatamodeld 文件 选中新的这个文件为current Xcddatamodeld 这样就轻松完成版本升级或增加字段
coredata内容 想灵活应用得多练练手