I have a Music App I am developing, and while I'm managing the TableViews, I'm sorting them into Sections. This is usually an easy process, but the with the way I manage I manage the data, it might not be a completely simple task.
I know it's not the best way to do it, but as the cell has multiple properties (titleLabel, textLabel, imageView), I store all the data in 3 separate arrays. When organising the songs by title, for section header, I use a predicate to set the titleLabel, so by using this code.
NSArray *predict = [mainArrayAll filteredArrayUsingPredicate:predicate];
cell.titleLabel.text = [predict objectAtIndex:indexPath.row];
Unfortunately, I also have a otherArrayAll, and others. These all have data such as the artist name, album artwork and so need to be relative to the songs they are for. Is there a way to reorder these other arrays in the same way the mainArrayAll array is? So the relative data is kept together?
In the above case I would suggest you to create a model class implementation to store all the values. Following MVC architecture is the best way here.
For eg:-
@interface Music : NSObject {}
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *artistName;
@property (nonatomic, strong) NSString *albumName;
//etc...
@end
Now if you want to create an array of music, do it as:
Music *myMusic1 = [[Music alloc] init];
myMusic1.title = @"name";
myMusic1.artistName = @"artist";//etc.. do this in a loop based on other contents array
NSMutableArray *array = [NSMutableArray arrayWithObjects:myMusic1, myMusic2, ... nil];
Now to sort this array:
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
return [a.title compare:b.title];
}];
If you want to use predicates:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K contains %@", @"title", @"name"];
NSArray *predict = [mainArrayAll filteredArrayUsingPredicate:predicate];
If you want to use these properties in a table view or so, you can use it as:
NSString *title = [[sortedArray objectAtIndex:indexPath.row] title];
NSString *artistName = [[sortedArray objectAtIndex:indexPath.row] artistName];