How to use NSPredicate to filter NSMutableSet which contains composite object from other Class?

本小妞迷上赌 提交于 2019-12-06 13:04:01

You have overloaded the meaning of -removeSong: and it has caused you confusion. In Playlist, -removeSong: takes a Song instance, but in Collection, -removeSong: takes a NSString instance for the song title.

The problem is you pass an instance of a Song to the version which expects an NSString.

- (void)removeSong:(NSString *)zSong
{
    NSSet *targets = [self lookUpTitle:zSong];
    // …
}

Should either be

- (void)removeSong:(Song *)aSong
{
    NSSet *targets = [self lookUpTitle:aSong.title];
    // …
}

or

- (void)removeSongWithTitle:(NSString *)aTitle
{
    NSSet *targets = [self lookUpTitle:aTitle];
    // …
}

I changed the name of the second version of the method to clearly show what the expected parameter is. When you want to use the second version, you would pass the message [myCollection removeSongWithTitle:aSong.title]

You don't need to use -predicateWithBlock, it should be sufficient to use the following predicate in your case

[NSPredicate predicateWithFormat:@"SELF.title CONTAINS %@", @"Layla"];

EDIT

Jeffery Thomas is right, the problem is in this line - in fact the compiler gives a warning

 [myCollection removeSong:aSong];

you're passing to the -removeSong: a Song object, not the song's title. If you want to pass to -removeSong: a Song object changes the method signature from - (void)removeSong:(NSString *)songTitle to -(void)removeSong:(Song*)song and change accordingly the method implementation to pass to the predicate the song's title which is a NSString

- (void) removeSong: (Song *)zSong {

    //remove from reference playlist
    NSSet *targets = [self lookUpTitle:zSong.title];

    if ([targets count]>0) {
        [self.masterSongs minusSet:targets];

        for (Playlist *playlist in self.listOfPlaylists) {
            // -all objects converts the set into array.

            [playlist.songList removeObjectsInArray:[targets allObjects]];
        }
    }
}

From now on, please do not ignore compiler warnings to avoid passing days debugging this kind of subtle errors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!