2012-03-30 73 views
1

我正在使用MPMediaQuery从库中获取所有艺术家。我想它的返回唯一名称,但问题是我的图书馆中有艺术家,如“Alice In Chains”和“Alice In Chains”。第二个“Alice In Chains”在最后有一些空格,所以它返回两个。我不想那样。继承人的代码...从MPMediaQuery获取独特的艺术家名字

MPMediaQuery *query=[MPMediaQuery artistsQuery]; 
    NSArray *artists=[query collections]; 
    artistNames=[[NSMutableArray alloc]init]; 
    for(MPMediaItemCollection *collection in artists) 
    { 
     MPMediaItem *item=[collection representativeItem]; 
     [artistNames addObject:[item valueForProperty:MPMediaItemPropertyArtist]]; 
    } 
    uniqueNames=[[NSMutableArray alloc]init]; 
    for(id object in artistNames) 
    { 
     if(![uniqueNames containsObject:object]) 
     { 
      [uniqueNames addObject:object]; 
     } 
    } 

任何想法?

回答

0

一种可能的解决方法是测试艺术家名称的前导和/或尾随空格。您可以检查字符串的第一个字符和最后一个字符以获得NSCharacterSetwhitespaceCharacterSet的会员资格。如果为true,则使用NSStringstringByTrimmingCharactersInSet方法修剪所有前导和/或尾部空白。然后,您可以将修剪的字符串或原始字符串添加到NSMutableOrderedSet。该组有序的将只接受不同的对象,因此没有重复的艺术家的名字将被添加:

MPMediaQuery *query=[MPMediaQuery artistsQuery]; 
NSArray *artists=[query collections]; 
NSMutableOrderedSet *orderedArtistSet = [NSMutableOrderedSet orderedSet]; 

for(MPMediaItemCollection *collection in artists) 
{ 
    NSString *artistTitle = [[collection representativeItem] valueForProperty:MPMediaItemPropertyArtist]; 
    unichar firstCharacter = [artistTitle characterAtIndex:0]; 
    unichar lastCharacter = [artistTitle characterAtIndex:[artistTitle length] - 1]; 

    if ([[NSCharacterSet whitespaceCharacterSet] characterIsMember:firstCharacter] || 
     [[NSCharacterSet whitespaceCharacterSet] characterIsMember:lastCharacter]) { 
     NSLog(@"\"%@\" has whitespace!", artistTitle); 
     NSString *trimmedArtistTitle = [artistTitle stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
     [orderedArtistSet addObject:trimmedArtistTitle]; 
    } else { // No whitespace 
     [orderedArtistSet addObject:artistTitle]; 
    } 
} 

您也可以从返回数组排序,如果你需要将其设置:

NSArray *arrayFromOrderedSet = [orderedArtistSet array]; 
相关问题