Skip to content

Instantly share code, notes, and snippets.

@kenmaz
Last active August 29, 2015 14:05
Show Gist options
  • Save kenmaz/8eaabc506ca844fb7cf6 to your computer and use it in GitHub Desktop.
Save kenmaz/8eaabc506ca844fb7cf6 to your computer and use it in GitHub Desktop.
CoreDataでatomicにsaveする ref: http://qiita.com/kenmaz/items/89e50f94262a4d0547c5
User
-uid
-name
[
{
"uid": 1,
"name": "kentaro"
},
{
"uid": 2,
"name": "yamada"
}
...
]
//APIアクセスしてレスポンス取得
NSNumber* uid = ..;
NSString* name = ...
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *ctx) {
User* user = [User MR_findFirstByAttribute:@"uid" withValue:uid inContext:ctx];
if (user == nil) {
user = [User MR_createInContext:ctx];
user.uid = uid;
}
person.name = name;
} completion:^(BOOL success, NSError *error) {
assert(success);
}];
int cnt = [Person MR_countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"uid = 1"]];
NSLog(@"count = %d", cnt);
//> count:100
static dispatch_queue_t serialQueue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
serialQueue = dispatch_queue_create("net.kenmaz.serialqueue", DISPATCH_QUEUE_SERIAL);
});
dispatch_async(serialQueue, ^{
//ここから〜
NSManagedObjectContext* ctx = [NSManagedObjectContext MR_context];
User* user = [User MR_findFirstByAttribute:@"uid" withValue:uid inContext:ctx];
if (user == nil) {
user = [User MR_createInContext:ctx];
user.uid = uid;
}
person.name = name;
[ctx MR_saveToPersistentStoreAndWait];
//〜ここまで排他的に実行
});
int cnt = [Person MR_countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"uid = 1"]];
NSLog(@"count = %d", cnt);
//> count:1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment