Sorting UITableView

5.3k views Asked by At

I want to do a basic sorting of a UITableView that is generated from MPMediaQuery.

What I want is to just have a basic songs list that sorts the songs into sections of A, B, C, D, etc. Shouldn't be hard, but every tutorial I've tried to follow ends up no giving me those results at all.

Any help would be wonderful. Here is my basic code. I realize this is not even close to having what I want accomplished, but I figured it would be easier for a seasoned developer to help me from this point then the mess I was in.

How I generate my data:

MPMediaQuery *musicLibraryQuery = [[MPMediaQuery alloc] init];
NSArray *musicLibraryArray = [musicLibraryQuery items];
songLibrary = [NSMutableArray arrayWithArray:musicLibraryArray];

These are my UITableView methods:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [songLibrary count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"SongCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    MPMediaItem *song = [[songLibrary objectAtIndex:[indexPath row]] representativeItem];

    cell.textLabel.text = [song valueForProperty:MPMediaItemPropertyTitle];

    return cell;
}
3

There are 3 answers

0
Shankar BS On

u need to sort array for example


songLibrary = [musicLibraryArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];


0
Nishith Shah On

If there is Dictionary as object in your Array and you want to sort array for perticular key then do this :

static NSString* const keyToSortBy = @"keyToSortBy";

NSArray * sortedArray = [array sortedArrayUsingComparator:^(id obj1, id obj2) {
    NSString *s1 = [obj1 objectForKey:keyToSortBy];
    NSString *s2 = [obj2 objectForKey:keyToSortBy];
    return [s1 caseInsensitiveCompare:s2];
}];
0
Prince Kumar Sharma On

Use this ,might this will be useful

songLibrary=[songLibrary sortedArrayUsingSelector:@selector(compare:)];