如何使用YapDatabase更新数据库记录

时间:2016-08-18 01:06:04

标签: ios objective-c yapdatabase

我使用Mantle作为模型框架。我有一个如下模式:

Season.h
@interface Season : MTLModel <MTLJSONSerializing>

@property (nonatomic, copy) NSNumber *seasonID;
@property (nonatomic, strong) NSArray *episodes;

Season.m
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return @{
             @"seasonID": @"id",
             @"episodes": @"episodes"
             };
}

Episode.h

@interface Episode : MTLModel <MTLJSONSerializing>

@property (nonatomic, copy) NSNumber *watched;

你可以看到这个季节有很多集。所以我使用YapDatabase将季节保存到数据库:

[[DatabaseUtility sharedUtility].database.newConnection asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction * _Nonnull transaction) {
            [transaction setObject:season forKey:season.seasonID.stringValue inCollection:kSeason];
        } completionBlock:^{

        }];

情况是我想更新剧集的观看价值。下面的工作会怎样?

[[DatabaseUtility sharedUtility].database.newConnection asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction * _Nonnull transaction) {
            [transaction setObject:episode forKey:episode.episodeID.stringValue inCollection:kEpisode];
        } completionBlock:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            });
        }];

1 个答案:

答案 0 :(得分:0)

首先,您可以尝试读取完成块中的值。并检查它是否更新。我也认为YapDatabase在主线程上执行完成块,所以你不需要dispatch_async(需要仔细检查这个信息)

当您在事务中setObject新对象时,它将被更新!

有一些很好的机制可以帮助您观察所有的变化。我在谈论Views, Mappings and Long-live transactions