運行環境:
OS X Yosemite 10.10.3
Xcode 6.3.1
MagicalRecord 2.3.0
工程配置:
1. 新建一個項目,注意在向導中不要勾選Core Data。
2. Product ->CocoaPods->Create/Edit Podfile 刪除里面的數據然后在里面填寫
platform :ios, '8.3'
pod 'MagicalRecord', '~> 2.3.0'
3. Product ->CocoaPods->Install Pods 等待下載完畢即可
4. 添加#import "MagicalRecord.h"到PCH文件中。
創建模型文件
下面創建一個名為Person的模型,有age、firstname、lastname三個字段。
1. 創建一個名為Model的模型文件。 (File > New File… > Core Data > Data Model > Next > Create)
2. 點擊左下角的Add Entity,更改Entity的名字為Person。
3. 為Entity添加三個Attribute:age(Integer16)、firstname(string)、lastname(string)。
4. 點擊File > New File… > NSManagedObject Subclass Next > 勾選Model > Next > 勾選Person > Next > > Create創建模型文件對應的類。
初始化
1. 首先在didFinishLaunchingWithOptions中添加以下代碼對Magical Record進行初始化:
[MagicalRecord setupCoreDataStackWithStoreNamed:@"MyDataBase.sqlite"];
2. 在applicationWillTerminate中添加清除代碼(自由選擇是否清除)
[MagicalRecord cleanUp];
添加數據
//? 實例化對象
Person *person = [Person MR_createEntity];
person.age = @17;
person.firstname = @"MTZ";
person.lastname = @"MYY";
//? 保存數據
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
查詢數據
//? 查找數據庫中的所有Person
NSArray *persons = [Person MR_findAll];
NSLog(@"%@",persons);
//? 查找數據庫中的第一條記錄
Person *person2 = [Person MR_findFirst];
NSLog(@"%@",person2);
//? 查找所有age屬性為25的Person記錄
NSArray *personsAgeEuqals17? = [Person MR_findByAttribute:@"age" withValue:[NSNumber numberWithInt:17]];
NSLog(@"%@",personsAgeEuqals17);
//? 查找所有的Person并按照first name排序
NSArray *personsSorted = [Person MR_findAllSortedBy:@"firstname" ascending:YES];
NSLog(@"%@",personsSorted);
修改數據
//? 取出表格中的第一條數據
Person *person3 = persons[0];
NSLog(@"%@",person3.lastname);
person3.lastname = @"MaTianZe";
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
NSLog(@"%@",person3.lastname);
刪除數據
//? 查找數據庫中的第一條記錄
Person *person4 = [Person MR_findFirst];
//? 刪除數據
[person4 MR_deleteEntity];
//? 記得保存哦
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
MesaSQLite一些屬性的含義
Z_PK? ? 是表的主鍵,從1開始遞增,唯一值
Z_ENT? 表在xcdatamodel 中的索引值,創建了5個表,Z_ENT的區間就是[1,5 ]
Z_OPT? 表示的是每條數據被操作的次數,初始化值為1,只要是增刪改查都會加1