我在我的应用程序中使用核心数据。 我知道如何将一个新对象插入其中。将歌曲信息存储到其中。 下面是我的表结构
song_id
song_title
song_description
Songs *aSong = (Poem *)[NSEntityDescription insertNewObjectForEntityForName:@"Songs" inManagedObjectContext:myManagedObjectContext];
这里我想知道如何在将对象再次插入到表中之前检查 song_id 是否已经可用。
我的意思是在插入新对象之前,我如何检查它是否存在。
还有如何检查表是否为空?
请告诉我,谢谢
最佳答案
NSError * error;
NSFetchRequest * checkExistance = [[NSFetchRequest alloc] init];
[checkExistance setEntity:[NSEntityDescription entityForName:NSStringFromClass([yourClass class]) inManagedObjectContext:yourManagedContext]];
[checkExistance setFetchLimit:1];
[checkExistance setPredicate:[NSPredicate predicateWithFormat:@"ID == %@", yourID]];
Songs *yourSong = [[managedObjectContext executeFetchRequest:checkExistance error:&error] lastObject];
现在如果 yourSong 存在,即不为 null 而不是它的 id 存在。
希望这对您有所帮助。
关于iphone - iOS 核心数据 - 插入前如何检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11288075/