關於Core Data的一些整理(一)

来源:http://www.cnblogs.com/jackma86/archive/2016/01/14/5130926.html
-Advertisement-
Play Games

關於Core Data的一些整理(一)在Xcode7.2中只有Mast-Debug和Single View中可以勾選Use Core Data如果勾選了Use Core Data,Xcode會自動在AppDelegate中幫你生成Core Data的核心代碼,並且自動生成.xcdatamodeld數...


關於Core Data的一些整理(一)

在Xcode7.2中只有Mast-Debug和Single View中可以勾選Use Core Data

如果勾選了Use Core Data,Xcode會自動在AppDelegate中幫你生成Core Data的核心代碼,並且自動生成.xcdatamodeld數據文件  
  1 //Appdelegate.h中
  2 #import <UIKit/UIKit.h>
  3 #import <CoreData/CoreData.h>
  4 
  5 @interface AppDelegate : UIResponder <UIApplicationDelegate>
  6 
  7 @property (strong, nonatomic) UIWindow *window;
  8 
  9 @property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
 10 @property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
 11 @property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
 12 
 13 - (void)saveContext;
 14 - (NSURL *)applicationDocumentsDirectory;
 15 
 16 
 17 @end
 18 
 19 
 20 
 21 //Appdelegate.m中系統幫助生成的代碼
 22 - (void)applicationWillTerminate:(UIApplication *)application {
 23   // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
 24   // Saves changes in the application's managed object context before the application terminates.
 25   [self saveContext];
 26 }
 27 
 28 #pragma mark - Core Data stack
 29 
 30 @synthesize managedObjectContext = _managedObjectContext;
 31 @synthesize managedObjectModel = _managedObjectModel;
 32 @synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
 33 
 34 - (NSURL *)applicationDocumentsDirectory {
 35     // The directory the application uses to store the Core Data store file. This code uses a directory named "qq100858433.JMHitList" in the application's documents directory.
 36     return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
 37 }
 38 
 39 - (NSManagedObjectModel *)managedObjectModel {
 40     // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
 41     if (_managedObjectModel != nil) {
 42         return _managedObjectModel;
 43     }
 44     NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"JMHitList" withExtension:@"momd"];
 45     _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
 46     return _managedObjectModel;
 47 }
 48 
 49 - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
 50     // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
 51     if (_persistentStoreCoordinator != nil) {
 52         return _persistentStoreCoordinator;
 53     }
 54     
 55     // Create the coordinator and store
 56     
 57     _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
 58     NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"JMHitList.sqlite"];
 59     NSError *error = nil;
 60     NSString *failureReason = @"There was an error creating or loading the application's saved data.";
 61     if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
 62         // Report any error we got.
 63         NSMutableDictionary *dict = [NSMutableDictionary dictionary];
 64         dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
 65         dict[NSLocalizedFailureReasonErrorKey] = failureReason;
 66         dict[NSUnderlyingErrorKey] = error;
 67         error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
 68         // Replace this with code to handle the error appropriately.
 69         // 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.
 70         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
 71         abort();
 72     }
 73     
 74     return _persistentStoreCoordinator;
 75 }
 76 
 77 
 78 - (NSManagedObjectContext *)managedObjectContext {
 79     // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
 80     if (_managedObjectContext != nil) {
 81         return _managedObjectContext;
 82     }
 83     
 84     NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
 85     if (!coordinator) {
 86         return nil;
 87     }
 88     _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
 89     [_managedObjectContext setPersistentStoreCoordinator:coordinator];
 90     return _managedObjectContext;
 91 }
 92 
 93 #pragma mark - Core Data Saving support
 94 
 95 - (void)saveContext {
 96     NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
 97     if (managedObjectContext != nil) {
 98         NSError *error = nil;
 99         if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
100             // Replace this implementation with code to handle the error appropriately.
101             // 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.
102             NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
103             abort();
104         }
105     }
106 }
107 
108 @end

假如你在.xcdatamodeld中生成瞭如下實體和實體屬性:

 

那麼在VC中獲取資料庫內容和添加資料庫內容的代碼如下:
 1   //從Core Data中獲得已有數據
 2   id appDelegate = [UIApplication sharedApplication].delegate;
 3   NSManagedObjectContext *managedContext = [appDelegate managedObjectContext];
 4   NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
 5   @try {
 6     self.people = [NSMutableArray arrayWithArray:[managedContext executeFetchRequest:fetchRequest error:nil]];
 7   }
 8   @catch (NSException *exception) {
 9     NSLog(@"Could not fetch %@", [exception userInfo]);
10   }
11   @finally {
12     NSLog(@"Fetch Successful");
13   }
14   
15   //為資料庫添加實體實例
16   id appDelegate = [UIApplication sharedApplication].delegate;
17   //NSManagedObjectContext可以看做記憶體中用來處理managedObjects的暫存器
18   NSManagedObjectContext *mangedContext = [appDelegate managedObjectContext];
19   //下麵兩種方法都可以獲得Person實體
20 //  NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:mangedContext];
21 //  NSManagedObject *person = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:mangedContext];
22 //  [person setValue:name forKey:@"name"];
23   NSManagedObject *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:mangedContext];
24   [person setValue:name forKey:@"name"];
25   @try {
26     [mangedContext save:nil];
27     [self.people addObject:person];
28   }
29   @catch (NSException *exception) {
30     NSLog(@"Could not save %@", [exception userInfo]);
31   }
32   @finally {
33     NSLog(@"Save Successfullt!");
34   }

 

     
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 單例模式在程式設計中非常的常見,一般來說,某些類,我們希望在程式運行期間有且只有一個實例,原因可能是該類的創建需要消耗系統過多的資源、花費很多的時間,或者業務上客觀就要求了只能有一個實例。一個場景就是:我們的應用程式有一些配置文件,我們希望只在系統啟動的時候讀取這些配置文件,並將這些配置保存在內.....
  • .h文件:#pragma once/****************************** @filename: Singleton.h* @author: kzf* @version: 1.0* @date: 2011/11/14 * @describe...
  • meta相關:CSS相關: -webkit-overflow-scrolling:touch;快速滾動和回彈的效果,看上去和原生app的效率都有得一拼。-webkit-overflow-scrolling創建了帶有硬體加速的系統級控制項,所以效率很高。但是這相對是耗更多記憶體的,最好在產生了非常大面積的...
  • 1、Gooflow特點1.1 跨瀏覽器可相容IE7--IE10, FireFox, Chrome, Opera等幾大內核的瀏覽器,且不需要瀏覽器再加裝任何控制項。1.2 多系統相容性、可移植性由於只包括前臺UI,因此二次開發者可很方便將本插件用在任何一種需要流程圖的B/S系統應用上,流程圖的詳細實現邏...
  • /** 判斷是否是快速點擊 */ private static long lastClickTime; public static boolean isFastDoubleClick() { long time = System.currentTimeMillis(...
  • 如圖設置的一種引導頁的開啟這個引用時先將圖片進行一個動畫當動畫結束時進入到了引導頁面 下麵的小圖片 當點擊的時候ViewPager消失 再點擊時ViewPager在顯示出來先看開啟界面 上面的動畫還是值得借鑒的package com.demo.activity;import com.demo.pul...
  • 1. 添加一個Target這裡是添加一個Test 項目這裡添加新的targetTest與Release 也是同上的操作
  • 1 查看遠程分支123456789101112131415$ git branch -a* br-2.1.2.2masterremotes/origin/HEAD -> origin/masterremotes/origin/br-2.1.2.1remotes/origin/br-2.1.2.2re...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...