iOS XML JSON SQLite CoreData 数据持久化
一、文件操作
2、相关方法:
# 使用NSSearchPathForDiretoriesInDomains()方法只能定位Caches目录和Documents目录
NSArray *paths = NSSearchPathForDiretoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)
# NSHomeDirectory();可以取得应用的根目录
e.g 通过home取tmp目录
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp/myFile.txt"];
# 使用资源文件:
# 应用安装到设备上后,资源文件是在app(即home目录)目录下的
e.g 获取资源文件
NSString *filePath = [[NSBundle mainBundle] pathForResourcce:@"f" ofType:@"txt"];
NSStirng *fileContent = [[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error nil];
;
* 1、sqlite3 *db,数据库句柄,跟文件句柄FILE很类似
* 2、sqlite3_stmt *stmt,这个相当于ODBC的Command对象,用于保存编译好的SQL语句
* 3、sqlite3_open() 打开数据库,没有数据库时创建
* 4、sqlite3_exec() 执行非查询的sql语句
* 5、Sqlite3_step() 在调用sqlite3_prepare后,使用这个函数在记录集中移动
* 6、sqlite3_close()关闭数据库
*
* 还有一系列用于从记录集字段中获取数据,e.g
* 1、sqlite3_column_text() 取text类型的数据
* 2、sqlite3_column_blob() 取blob类型数据
* 3、sqlite3_column_int() 取int类型数据
* 数据库操作要添加 libsqlite3.dylib 静态库
* 包含头文件: import "sqlite3.h"
*/
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
// 解析完一个元素时回调的方法
- /*
- {
- "aps":
- {
- "alert" :
- {
- "body" : "a msg come!"
- },
- "bage": 3,
- "sound" : "def.mp3"
- }
- }
- */
- NSString *strJson = @"{\"aps\":{\"alert\":{\"body\":\"a msg come!\"}, \"bage\":3, \"sound\":\"def.mp3\"}}";
- // result中即为解析出来的json文件,通过valueForKey即可读到相应的数据
- NSDictionary *result = [strJson objectFromJSONString];
- NSLog(@"%@", result);
- NSString *myJsonPath = [[NSBundlemainBundle] pathForResource:@"my"ofType:@"json"];
- NSString *myJsonStr = [NSStringstringWithContentsOfFile:myJsonPath encoding:NSUTF8StringEncodingerror:nil];
- NSLog(@"myJsonStr : %@", myJsonStr);
- NSDictionary *myResult = [myJsonStr objectFromJSONString];
- NSLog(@"myJson : %@", myResult);
- // 生成json文件
- NSMutableDictionary *jsonDic = [[NSMutableDictionarydictionary] autorelease];
- NSMutableDictionary *alert = [[NSMutableDictionarydictionary] autorelease];
- NSMutableDictionary *aps = [[NSMutableDictionarydictionary] autorelease];
- [alert setObject:@"a msg come!"forKey:@"body"];
- [aps setObject:alert forKey:@"alert"];
- [aps setObject:@"3"forKey:@"bage"];
- [aps setObject:@"def.mp3"forKey:@"sound"];
- [jsonDic setObject:aps forKey:@"aps"];
- NSString *jsonStr = [jsonDic JSONString];
@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persisteneStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
- -(void)saveContext
- {
- NSError *error = nil;
- NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
- if (managedObjectContext != nil) {
- if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- }
- }
- #pragma mark - Core Data stack
- - (NSManagedObjectContext *)managedObjectContext
- {
- if (__managedObjectContext != nil) {
- return__managedObjectContext;
- }
- NSPersistentStoreCoordinator *coordinator = [selfpersisteneStoreCoordinator];
- if (coordinator != nil) {
- __managedObjectContext = [[NSManagedObjectContextalloc] init];
- [__managedObjectContextsetPersistentStoreCoordinator:coordinator];
- }
- return__managedObjectContext;
- }
- - (NSManagedObjectModel *)managedObjectModel
- {
- if (__managedObjectModel != nil) {
- return__managedObjectModel;
- }
- // 这里URLForResource:@"lich" 的名字(lich)要和你建立datamodel时候取的名字是一样的
- NSURL *modelURL = //[NSURL fileURLWithPath:[@"lich" stringByAppendingPathExtension:@"mom"]];
- [[NSBundlemainBundle] URLForResource:@"lich"withExtension:@"momd"];
- __managedObjectModel = [[NSManagedObjectModelalloc] initWithContentsOfURL:modelURL];
- return__managedObjectModel;
- }
- - (NSPersistentStoreCoordinator *)persisteneStoreCoordinator
- {
- if (__persistentStoreCoordinator != nil) {
- return__persistentStoreCoordinator;
- }
- NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
- NSURL *storURL = [NSURLfileURLWithPath:[docs stringByAppendingPathComponent:@"lich.sqlite"]];
- // 这个lich.sqlite名字无限制,就是一个数据库文件的名字
- // NSURL *storeNRL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"lich.sqlite"];
- // NSLog(@"storURL : %@", storeNRL);
- // NSLog(@"store : %@", storURL);
- NSError *error = nil;
- __persistentStoreCoordinator = [[NSPersistentStoreCoordinatoralloc] initWithManagedObjectModel:[selfmanagedObjectModel]];
- if (![__persistentStoreCoordinatoraddPersistentStoreWithType:NSSQLiteStoreTypeconfiguration:nilURL:storURL options:nilerror:&error]) {
- NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
- abort();
- }
- return__persistentStoreCoordinator;
- }
- - (void)applicationWillTerminate:(UIApplication *)application
- {
- // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
- [selfsaveContext];
- }
- // 按保存按钮,保存数据
- - (void)addButtonPressed
- {
- [self.titleFieldresignFirstResponder];
- [self.ageFieldresignFirstResponder];
- Entity *entity = (Entity *) [NSEntityDescriptioninsertNewObjectForEntityForName:@"Entity"inManagedObjectContext:self.context];
- [entity setTitle:self.titleField.text];
- [entity setAge:[NSNumbernumberWithInt:[self.ageField.textintValue]]];
- NSError *error;
- BOOL isSaveSuccess = [self.contextsave:&error];
- if (isSaveSuccess) {
- NSLog(@"save successful!");
- } else {
- NSLog(@"Error : %@, %@ ", error, [error userInfo]);
- }
- }
- // 按查找按钮,取出数据
- - (void)queryButtonPressed
- {
- // 创建取回数据请求
- NSFetchRequest *request = [[[NSFetchRequestalloc] init] autorelease];
- // 设置要检索的数据类型
- NSEntityDescription *des = [NSEntityDescriptionentityForName:@"Entity"inManagedObjectContext:self.context];
- // 设置请求实体
- [request setEntity:des];
- // 指定结果的排序方式
- NSSortDescriptor *sortDescriptor = [[[NSSortDescriptoralloc] initWithKey:@"age"ascending:NO] autorelease];
- NSArray *sortDescriptions = [[[NSArrayalloc] initWithObjects:sortDescriptor, nil] autorelease];
- [request setSortDescriptors:sortDescriptions];
- NSError *error = nil;
- NSMutableArray *mutableFetchResult = [[self.contextexecuteFetchRequest:request error:&error] mutableCopy];
- if (mutableFetchResult == nil) {
- NSLog(@"Error : %@ , %@", error, [error userInfo]);
- }
- self.entities = mutableFetchResult;
- NSLog(@"The count of entry: %d", [self.entitiescount]);
- for (Entity *entity inself.entities) {
- NSLog(@"Title : %@ --------- Age: %d", entity.title, [entity.ageintValue]);
- }
- [mutableFetchResult release];
- }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。