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) 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];
- }