【问题标题】:iOS Core data - how to check before insertingiOS核心数据——插入前如何检查
【发布时间】:2012-07-02 05:13:56
【问题描述】:

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

song_id

song_title

song_description

Songs *aSong = (Poem *)[NSEntityDescription insertNewObjectForEntityForName:@"Songs" inManagedObjectContext:myManagedObjectContext];  

这里我想知道如何在再次将对象插入表中之前检查 song_id 是否已经可用。

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

还有如何检查表是空的?

请告诉我,谢谢

【问题讨论】:

    标签: iphone ios core-data ios4


    【解决方案1】:
    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 存在,即不为空而不是它的 id 存在。

    希望这会有所帮助。

    【讨论】:

    • 您好,感谢您的回复。所以你的意思是我可以检查 if ( yourSong ){ nslog@"song is avaialble already so skip inserting");} else{ nslog(@"save here");} 对吗?
    • 在这里它给予 n 采取(道德)因为我们都是社区成员的同事。 :D
    【解决方案2】:

    您可以使用 NSEntityDescription 方法从托管对象模型中获取实体 entityForName:inManagedObjectContext:

    现在 executeFetchRequest 方法将提供数组,我们可以从中知道记录是否退出。根据您的要求,您可以插入新记录

    参考Fetching Managed Objects链接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 2023-03-15
      • 1970-01-01
      • 2015-07-20
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多