【问题标题】:Core Data to-many relationship as NSOrderedSet核心数据多对多关系作为 NSOrderedSet
【发布时间】:2014-03-20 11:29:30
【问题描述】:

我的核心数据模型:

Playlist
=======
name

songs (to-many relationship to Song objects, NSOrderedSet)

一个播放列表有多首歌曲,歌曲顺序很重要。
使用NSOrderedSet 我可以保持歌曲顺序,问题是当我想在表格视图中获取和呈现播放列表的歌曲时,我不知道如何使用NSFetchRequest 的优势。

这就是我获取播放列表歌曲的方式:

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Song"];
request.predicate = [NSPredicate predicateWithFormat:@"ANY playlists = %@", self.playlist];
request.sortDescriptors = // ???
request.fetchBatchSize = 20;

self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                    managedObjectContext:managedObjectContext
                                                                      sectionNameKeyPath:nil
                                                                               cacheName:nil];  

实际上这不起作用,因为NSFetchedResultsController 需要带有排序描述符的获取请求。

所以我有歌曲顺序,但我无法按照该顺序获取它们?

【问题讨论】:

    标签: ios iphone objective-c core-data nsfetchedresultscontroller


    【解决方案1】:

    我过去做过:

    将此方法添加到您的 Song NSManagedObject 子类:

    - (NSUInteger)indexInPlaylist
    {
        NSUInteger index = [self.playlist.songs indexOfObject:self];
        return index;
    }
    

    然后你可以在你的 NSFetchedResultsController 的排序描述符中使用这个方法:

    fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"indexInPlaylist" ascending:YES]];
    

    【讨论】:

    • 那么你的歌曲关系是多对多的,老实说我从未尝试过这种设置。
    • 如果核心数据是 SQL 备份,这不起作用,我收到以下错误:keypath indexInPlaylist not found in entity
    【解决方案2】:

    我认为这是不可能的,您需要以其他方式存储排序顺序。这是一个关于它的讨论:NSFetchedResultsController and NSOrderedSet relationships

    【讨论】:

      猜你喜欢
      • 2016-06-30
      • 1970-01-01
      • 2011-02-18
      • 2016-09-08
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      相关资源
      最近更新 更多