I am a beginner and maybe it is a trivial question. I have this method:
-(NSString *)getInfoFormediaItem:(MPMediaItemCollection *)list {
NSString *trackCount;
if ([list count] > 0) {
trackCount = [NSString stringWithFormat:NSLocalizedString(@"%lu Songs", @""), (unsigned long)[list count]];
} else if([list count] == 1) {
trackCount = [NSString stringWithFormat:NSLocalizedString(@"1 Song", @"")];
} else {
trackCount = [NSString stringWithFormat:NSLocalizedString(@"0 Song", @"") ];
}
return [NSString stringWithFormat:@"%@", trackCount];
}
I would like to call it here with a MPMediaItemCollection:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if( cell == nil )
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
}
MPMediaQuery *playlistsQuery = [MPMediaQuery playlistsQuery];
NSArray *playl = [playlistsQuery collections];
MPMediaItem *rowItem = [playl objectAtIndex:indexPath.row];
MPMediaItemCollection * collection = [[MPMediaItemCollection alloc] initWithItems:[NSArray arrayWithObject:rowItem]];
cell.detailTextLabel.text = [self getInfoFormediaItem:collection];
}
I would like to get the number of tracks in each playlist. It doesn't work. How do I fix? Thanks in advance!
Why are you using performSelector:withObject:
? Just call the method directly:
cell.detailTextLabel.text = [self getInfoFormediaItem:collection];
Why are you passing nil
to the withObject:
parameter? That's why your code goes to the else
. list
is nil
so [list count]
will always be 0
. You need to pass an actual instance of a MPMediaItemCollection
.
Why are you needlessly using stringWithFormat:
for the 1 and 0 count checks? Just do:
-(NSString *)getInfoFormediaItem:(MPMediaItemCollection *)list {
NSString *trackCount;
if ([list count] > 1) {
trackCount = [NSString stringWithFormat:NSLocalizedString(@"%lu Songs", @""), (unsigned long)[list count]];
} else if([list count] == 1) {
trackCount = NSLocalizedString(@"1 Song", @"");
} else {
trackCount = NSLocalizedString(@"0 Song", @"");
}
return trackCount;
}
Based on your updated question, your cellForRowAtIndexPath
code isn't correct for the getting the media collection. The collections
method returns an array of MPMediaCollection
objects, not MPMediaItem
objects. You need:
MPMediaQuery *playlistsQuery = [MPMediaQuery playlistsQuery];
NSArray *playl = [playlistsQuery collections];
MPMediaItemCollection *collection = playl[indexPath.row];
Now you can use collection
when you call getInfoFormediaItem:
.