嗨,
我希望获取所有具有playlist_index = 1的歌曲。我创建了一对多关系并生成了访问器。
但是,当我通过谓词获取歌曲时,尽管我已经向许多歌曲添加了相同的播放列表,但它总是只给我一首歌曲。通过将纯NSManagedObject
转换为coredata生成的模型对象,这就是我向歌曲添加播放列表的方式。
-(void) addPlaylistToAudio {
// Audio Coredata Model
Audio *audioManagedObject = [self getAudioManagedObject:self.artist];
PlaylistModel *playlistObj = [self.arrayPlaylist objectAtIndex:indexPath.row];
// Playlist Coredata Model
Playlist *playlistManagedObject = [self getPlaylistManagedObject:playlistObj];
[audioManagedObject addPlaylist_relationObject:playlistManagedObject];
[playlistManagedObject setAudio_relation:audioManagedObject];
// PLEASE CHECK HERE IF I AM ADDING CORRECTLY
NSManagedObjectContext *context = [[CoreDataHandler sharedInstance]
managedObjectContext];
NSError *error = nil;
if (![context save:&error]) {
}
else {
}
}
- (Audio *)getAudioManagedObject:(Artist *)artist {
// Create Predicate to fetch managed object.
NSPredicate *predicate = [NSPredicate
predicateWithFormat:@"track_index == %ld",artist.track_index];
// Get Predicate array of managed object.
NSArray *arrayAudioManagedObject = [[CoreDataHandler sharedInstance]
fetchAudioManagedObjectsWithPredicate:predicate havePredicate:TRUE];
// Managed object.
Audio *audioManagedObject = [arrayAudioManagedObject lastObject];
return audioManagedObject;
}
-(Playlist *)getPlaylistManagedObject:(PlaylistModel *)playlist {
// Create Predicate to fetch managed object.
NSPredicate *predicate = [NSPredicate
predicateWithFormat:@"playlist_index == %ld",playlist.playlist_index];
// Get Predicate array of managed object.
NSArray *arrayPlaylistManagedObject = [[CoreDataHandler sharedInstance]
fetchPlaylistManagedObjectsWithPredicate:predicate havePredicate:TRUE];
// Managed object.
Playlist *playlistManagedObject = [arrayPlaylistManagedObject
lastObject];
return playlistManagedObject;
}
获取:
NSPredicate *predicate_audio = [NSPredicate predicateWithFormat:@"ANY playlist_relation.playlist_index == %ld",self.playlistInfo.playlist_index];
NSArray *arraySongsManagedObject = [[CoreDataHandler sharedInstance] fetchAudioManagedObjectsWithPredicate:predicate_audio havePredicate:TRUE];
答案 0 :(得分:1)
我认为ANY
只会返回一个符合您条件的结果,您真正需要的是SUBQUERY
,您可以在其中用以下内容替换委托:
let predicate_audio = NSPredicate(format: "SUBQUERY(playlist_realtion, $x, $x.playlist_index == %ld).@count > 0", self.playlistInfo.playlist_index)
或在Objective-C
中NSPredicate *predicate_audio = [NSPredicate predicateWithFormat:@"SUBQUERY(playlist_realtion, $x, $x.playlist_index == %ld).@count > 0", self.playlistInfo.playlist_index]
请注意,$x
只是代表每个元素关系的占位符。
链接:
http://davidchuprogramming.blogspot.com/2016/10/one-to-many-relationship-and-subquery.html
让我知道它是否对您有用