iOS核心数据 - 插入前如何检查

use*_*878 2 iphone core-data ios4 ios

我在我的应用程序中使用核心数据.我知道如何在其中插入一个新对象.它将歌曲信息存储在其中.下面是我的表结构

song_id

song_title

song_description

Songs *aSong = (Poem *)[NSEntityDescription insertNewObjectForEntityForName:@"Songs" inManagedObjectContext:myManagedObjectContext];  
Run Code Online (Sandbox Code Playgroud)

在这里,我想知道如何在将表格再次插入表格之前检查song_id是否已经可用.

我的意思是在插入新对象之前,我该如何检查它是否存在.

还怎么检查表是空的?

请告诉我并感谢

Jan*_*mal 5

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];
Run Code Online (Sandbox Code Playgroud)

现在这里如果你的存在,即不存在而不存在id.

希望这可以帮助.