1

I am using MPMediaQuery to get all artists from library. Its returning unique names I guess but the problem is I have artists in my library like "Alice In Chains" and "Alice In Chains ". The second "Alice In Chains" has some white spaces at the end, so it returns both. I dont want that. Heres the code...

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];
        }
    }

Any ideas?

Akash Malhotra
  • 1,106
  • 1
  • 17
  • 30

1 Answers1

0

One possible workaround would be to test the artist names for leading and/or trailing whitespace. You could inspect the first and last character of the string for membership with NSCharacterSet whitespaceCharacterSet. If true, then trim all leading and/or trailing whitespace using the NSString stringByTrimmingCharactersInSet method. Then you could add either the trimmed string or the original string to a NSMutableOrderedSet. The ordered set will only accept distinct objects so no duplicate artist names will be added:

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];
    }
}

You can also return an array from the ordered set if you need it:

NSArray *arrayFromOrderedSet = [orderedArtistSet array];
Bryan Luby
  • 2,527
  • 22
  • 31