資料儲存:CoreData

一個孤獨的搬碼猿發表於2019-03-05

鎮樓圖

CoreData的簡單使用介紹(已User表為例)

重點類z

  • NSManagedObject

通過Core Data從資料庫中取出的物件,預設情況下都是NSManagedObject物件.
NSManagedObject的工作模式有點類似於NSDictionary物件,通過鍵-值對來存取所有的實體屬性.
setValue:forkey:儲存屬性值(屬性名為key);
valueForKey:獲取屬性值(屬性名為key). 每個NSManagedObject都知道自己屬於哪個NSManagedObjectContext


  • NSManagedObjectContext:管理物件上下文

負責資料和應用庫之間的互動(CRUD,即增刪改查、儲存等介面都在這個物件中).
所有的NSManagedObject都存在於NSManagedObjectContext中,所以物件和context是相關聯的
每個 context 和其他 context 都是完全獨立的
每個NSManagedObjectContext都知道自己管理著哪些NSManagedObject


  • NSManagedObjectModel:模型物件

Core Data的模型檔案


  • NSPersistentStoreCoordinator:儲存排程器

新增持久化儲存庫,CoreData的儲存型別(比如SQLite資料庫就是其中一種)
中間審查者,用來將物件圖管理部分和持久化部分捆綁在一起,負責相互之間的交流(中介一樣)


  • NSEntityDescription:

用來描述實體:相當於資料庫表中一組資料描述

User中欄位

@property (nonatomic) int16_t age;
@property (nonatomic) int64_t id;
@property (nullable, nonatomic, copy) NSString *name;
@property (nonatomic) BOOL sex;
複製程式碼

系統庫

#import <CoreData/CoreData.h>
複製程式碼

開啟資料庫

// 建立資料庫
    // 1. 例項化資料模型(將所有定義的模型都載入進來)
    // merge——合併
    self.managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
    
    // 2. 例項化持久化儲存排程,要建立起橋樑,需要模型
    self.persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];
    
    // 3. 新增一個持久化的資料庫到儲存排程
    // 3.1 建立資料庫儲存在沙盒的URL
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [[path stringByAppendingString:@"/"] stringByAppendingString:@"wudan.sqlite"];
    NSURL *pathUrl = [NSURL fileURLWithPath:filePath];
    
    // 3.2 開啟或者新建資料庫檔案
    // 如果檔案不存在,則新建之後開啟
    // 否者直接開啟資料庫
    NSError *error;
    @try {
        [self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:pathUrl options:nil error:&error];
        self.context = [[NSManagedObjectContext alloc] init];
        self.context.persistentStoreCoordinator = self.persistentStoreCoordinator;
    } @catch (NSException *exception) {
        NSLog(@"Error:%@",error);
    } @finally {
        NSLog(@"開啟資料庫");
    }
複製程式碼

查詢資料

  • 全部查詢
- (void)queryAllResult:(void(^)(NSArray *dataArray))result {
    NSMutableArray *array = [NSMutableArray array];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id > 0"];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    request.predicate = predicate;
    NSError *error;
    
    NSArray *re = [self.context executeFetchRequest:request error:&error];
    if (re.count != 0) {
        for (User *user in re) {
            [array addObject:user];
        }
    }
    result(array);
}
複製程式碼
  • 分頁查詢
- (void)queryUserInfoWithPageNo:(NSInteger)pageNo pageSize:(NSInteger)pageSize result:(void(^)(NSArray *dataArray))result {
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    NSSortDescriptor *scoreSort = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:true];
    request.sortDescriptors = @[scoreSort];
    request.fetchOffset = (pageNo - 1) * pageSize;
    request.fetchLimit = pageSize;
    
    NSError *error = nil;
    NSArray *re = [self.context executeFetchRequest:request error:&error];
    NSMutableArray *array = [NSMutableArray array];
    
    if (re.count != 0) {
        for (User *user in re) {
            [array addObject:user];
        }
    }
    result(array);
}
複製程式碼
  • 條件查詢
- (void)queryUserInfoByObject:(id)object value:(id)value result:(void(^)(NSArray *dataArray))result  {
    NSMutableArray *array = [NSMutableArray array];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ = '%@'", object, value]];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    request.predicate = predicate;
    NSError *error;
    
    NSArray *re = [self.context executeFetchRequest:request error:&error];
    if (re.count != 0) {
        for (User *user in re) {
            [array addObject:user];
        }
    }
    result(array);
}
複製程式碼

新增資料

- (void)addUserInfo:(NSInteger)userId name:(NSString *)name sex:(BOOL)sex age:(NSInteger)age success:(void(^)(void))success fail:(void(^)(void))fail {
    
    __block NSArray *array;
     [self queryUserInfoByObject:@"id" value:@(userId) result:^(NSArray * _Nonnull dataArray) {
         array = dataArray;
     }];
    
    if (array.count == 0) {
        
        User *user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.context];
        user.name = name;
        user.id = userId;
        user.sex = sex;
        user.age = age;
        
        NSError *error;

        @try {
            [self.context save:&error];
            success();
        } @catch (NSException *exception) {
            NSLog(@"%@", error);
            fail();
        } @finally {
            NSLog(@"新增");
        }
    } else {
        fail();
    }
}
複製程式碼

更新資料

- (void)updateUserInfo:(NSInteger)userId infoDic:(NSDictionary *)dic success:(void(^)(void))success fail:(void(^)(void))fail {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"id = %ld", userId]];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    request.predicate = predicate;
    NSError *error;
    
    if (dic.count > 0) {
        NSArray *re = [self.context executeFetchRequest:request error:&error];
        if (re.count > 0) {
            for (User *user in re) {
                [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                    [user setValue:obj forKey:key];
                }];
            }
        }
        
        @try {
            [self.context save:&error];
            success();
        } @catch (NSException *exception) {
            NSLog(@"%@", error);
            fail();
        } @finally {
            NSLog(@"更新");
        }
    }
}
複製程式碼

刪除資料

- (void)deleteUserInfo:(NSInteger)userId success:(void(^)(void))success fail:(void(^)(void))fail {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"id = %ld", userId]];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];
    request.predicate = predicate;
    NSError *error;
    
    NSArray *re = [self.context executeFetchRequest:request error:&error];
    if (re.count > 0) {
        @try {
            [self.context deleteObject:re.firstObject];
            [self.context save:nil];
            success();
        } @catch (NSException *exception) {
            NSLog(@"%@", error);
            fail();
        } @finally {
            NSLog(@"刪除資料");
        }
    } else {
        NSLog(@"資料庫中暫無該資料");
        fail();
    }
}
複製程式碼

相關文章