从(并排序)NSMutable数组

时间:2015-11-22 15:47:28

标签: objective-c arrays sorting

我一直在努力应该做一个相当简单的任务。

在viewController.h中我有:

@interface MoviesList : NSObject {    
}
@property NSString *aTitle;
@property NSDate *aReleaseYear;
@property NSString *aCharacter;
@end

在viewController.m中(fetchedData包含一个JSON响应,movieCount已经确定)我有:

NSMutableArray *moviesArray;

MoviesList *movieDetails = [[MoviesList alloc] init];

int myCount = 0;

while (myCount < movieCount) {     
        MoviesList *movieDetails = [[MoviesList alloc] init];
        // Insert character played into array.
        movieDetails.aCharacter = fetchedData[@"cast"][myCount][@"character"];

        // Insert movie title and release date into array.
        movieDetails.aTitle = fetchedData[@"cast"][myCount][@"title"];
        movieDetails.aReleaseYear = fetchedData[@"cast"][myCount][@"release_date"];

        [moviesArray addObject:movieDetails];

        NSLog(@"Title: %@",movieDetails.aTitle);
        NSLog(@"Release date: %@",movieDetails.aReleaseYear);
        NSLog(@"Character: %@",movieDetails.aCharacter);

        myCount++;

}
NSLog(@"moviesArray: %@",moviesArray);

当我使用断点运行并将鼠标悬停在电影上时#Array&#39;在上面的最后一行中,我可以看到它填充了正确的信息:

@"58 objects"
[0] = (MoviesList *) 0x7962b650
> NsObject
> _aTitle = blah blah
> _aReleaseYear = blah blah
> _aCharacter = blah blah...

所以看起来阵列正在正确填充。现在的问题是如何按发布日期对这些信息进行排序(我整天都在梳理这个论坛,看到了各种各样的排序答案,但我没有成功),然后通过NSLOG显示排序的数组。

任何帮助都表示赞赏,这个论坛似乎有丰富的知识,并且总是有人愿意提供帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

这段代码将按照aReleaseYear按升序排序moviesArray的内容:

NSSortDescriptor *ageDescriptor = [[NSSortDescriptor alloc] initWithKey:@"aReleaseYear" ascending:YES];
NSArray *sortDescriptors = @[ageDescriptor];
NSArray *sortedArrayByReleaseYear = [moviesArray sortedArrayUsingDescriptors:sortDescriptors];

如果您希望它们按降序排列,请将升序更改为NO。