How to update database record using YapDatabase

214 Views Asked by At

I am using Mantle as model framework. I have a mode like below:

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;

As you can see the season have many episodes. So I save the Season to database using YapDatabase:

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

        }];

The situation is I want to update episode's watched value. So will below work?

[[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

There are 1 best solutions below

0
On

First of all, you can try reading a value in a completion block. And check if it is updated or not. I also think that YapDatabase executes completion block on Main Thread, so you don't need dispatch_async (need to double check this info)

When you setObject a new object in transaction it will be updated!

There are some great mechanisms that help you to observe all the changes. I'm talking about Views, Mappings and Long-live transactions.