文件数据IOS学习:ios中的数据持久化初级(文件、xml、json、sqlite、CoreData)
PS:今天上午,非常郁闷,有很多简略基础的问题搞得我有些迷茫,哎,代码几天不写就忘。目前又不当COO,还是得用心记代码哦!
一、文件操作
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]; }
文章结束给大家分享下程序员的一些笑话语录:
人在天涯钻,哪儿能不挨砖?日啖板砖三百颗,不辞长做天涯人~
---------------------------------
原创文章 By
文件和数据
---------------------------------