Skip to content

Commit

Permalink
NSManagedObjectContextのsave関連メソッドでNSErrorを返すように修正
Browse files Browse the repository at this point in the history
  • Loading branch information
suterusu committed Oct 6, 2023
1 parent fb9f7df commit d134e17
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
2 changes: 2 additions & 0 deletions Sources/UBICoreData/NSManagedObjectContext+UBICoreData.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ NS_ASSUME_NONNULL_BEGIN
- (NSManagedObjectContext *)newPrivateQueueContext;

- (BOOL)save;
- (BOOL)saveWithError:(NSError **)error;
- (BOOL)saveToPersistentStore;
- (BOOL)saveToPersistentStoreWithError:(NSError **)error;

@end

Expand Down
26 changes: 20 additions & 6 deletions Sources/UBICoreData/NSManagedObjectContext+UBICoreData.m
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,39 @@ - (NSManagedObjectContext *)newPrivateQueueContext
return context;
}

- (BOOL)save
-(BOOL)save
{
return [self saveWithError:nil];
}

- (BOOL)saveWithError:(NSError **)error
{
if (![self hasChanges]) {
return YES;
}

NSError* error = nil;
NSError* localError = nil;

if (![self save:&error]) {
if (![self save:&localError]) {
#ifdef DEBUG
NSLog(@"%s - error: %@", __PRETTY_FUNCTION__, [error userInfo]);
NSLog(@"%s - error: %@", __PRETTY_FUNCTION__, [localError userInfo]);
#endif
if (error) {
*error = localError;
}

return NO;
}

return YES;
}

- (BOOL)saveToPersistentStore
{
return [self saveToPersistentStoreWithError:nil];
}

- (BOOL)saveToPersistentStoreWithError:(NSError **)error
{
NSSet *insertedObjects = self.insertedObjects;
if (insertedObjects.count > 0) {
Expand All @@ -58,7 +72,7 @@ - (BOOL)saveToPersistentStore
}
}

if ([self save]) {
if ([self saveWithError:error]) {
NSManagedObjectContext *context = [self parentContext];

if (!context) {
Expand All @@ -68,7 +82,7 @@ - (BOOL)saveToPersistentStore
__block BOOL save = NO;

[context performBlockAndWait:^{
save = [context saveToPersistentStore];
save = [context saveToPersistentStoreWithError:error];
}];

return save;
Expand Down

0 comments on commit d134e17

Please sign in to comment.