2012-04-24 98 views
2

我有以下几点:搜索多种类型与MPMediaPropertyPredicate

MPMediaPropertyPredicate *titlePredicate = [MPMediaPropertyPredicate predicateWithValue:textString 
                      forProperty:MPMediaItemPropertyTitle 
                     comparisonType:MPMediaPredicateComparisonContains]; 

NSSet *predicateSet = [NSSet setWithObject:titlePredicate]; 
MPMediaQuery *searchQuery = [[MPMediaQuery alloc] initWithFilterPredicates:predicateSet]; 
NSArray *itemsFromTextQuery = [searchQuery items]; 

for (MPMediaItem *song in itemsFromTextQuery) 
{ 
    [arrayOfSongItems addObject:song]; 
} 

伟大的工程,但只有搜索的曲目的标题。我希望它能返回标题,艺术家和专辑名称的结果。

回答

4

尝试下面的代码

MPMediaQuery* query = [MPMediaQuery albumsQuery]; 

[query addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:self.strArtist forProperty:MPMediaItemPropertyArtist]] 

[query addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:self.strTitle forProperty:MPMediaItemPropertyAlbumTitle]]; 
+0

这假设两个字符串是不同的。我希望能够像iPhone的iPod应用程序的搜索表一样显示艺术家和/或专辑&或找到的曲目。 – daidai 2013-02-06 12:19:51

4

这个工作对我来说:

MPMediaQuery *searchQuery = [[MPMediaQuery alloc] init]; 
NSPredicate *test = [NSPredicate predicateWithFormat:@"title contains[cd] %@ OR albumTitle contains[cd] %@ OR artist contains[cd] %@", searchString, searchString, searchString]; 
NSArray *filteredArray = [[searchQuery items] filteredArrayUsingPredicate:test]; 

//NSLog(@"%@", [filteredArray valueForKeyPath:@"title"]); 

for (MPMediaItem *song in filteredArray) 
{ 
    [arrayOfSongItems addObject:song]; 
} 

我基本上后过滤正从媒体查询的所有项目。我不认为我的解决方案比首先过滤查询更好,但绝对比单独搜索三次更好。或者多次遍历数组。

+0

这一切都很好 - 但是你怎么知道它是一首曲目,专辑还是艺术家? – daidai 2013-02-07 04:21:42

+0

如果你需要这些信息,那么最新的问题不是使用3个查询?你可以使用我的解决方案,然后在for循环中检查这三个值if([song.title isEqualToString:searchString]){}'等等。如果你使用3个查询并且想合并它们,你可以在添加新的元素与你的数组与'if([arr indexOfObject:@“new Item”== NSNotFound){// add new Item}' – 2013-02-07 13:59:05

+0

问题是性能。在整个图书馆中运行3次查询可能需要几秒钟的时间 - 苹果音乐播放器可以很快完成。 – daidai 2013-09-18 06:05:08