Multiple NSMutableArrays, one sorted by Predicate, others reordered relatively

南笙酒味 提交于 2020-01-05 07:37:28

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/15304811/multiple-nsmutablearrays-one-sorted-by-predicate-others-reordered-relatively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!