如何一次对plist数据进行排序和过滤?

时间:2011-12-19 16:26:53

标签: objective-c sorting plist filtering

Objective-C新手在这里,

我试图从plist中提取数据,过滤它,然后排序。 我在其他页面上使用下面的排序方法,它工作正常。

我确实在下面注明的路线上收到此警报: 从'NSMutableArray *'

分配给'NSArray *'的指针类型不兼容

我收到此错误:

2011-12-19 11:16:39.142 ATCScontacts[2511:707] -[__NSArrayI sortUsingDescriptors:]: unrecognized selector sent to instance 0x159cf0
2011-12-19 11:16:39.149 ATCScontacts[2511:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI sortUsingDescriptors:]: unrecognized selector sent to instance 0x159cf0'

接口文件:

#import <UIKit/UIKit.h>

@class customDetailViewController;
@interface contactsViewController : UITableViewController
{
    NSMutableArray *contacts_;
}

@property (nonatomic, retain) NSMutableArray* contacts;

实施档案:

- (void)viewDidLoad
{
    [super viewDidLoad];

//Load plist
    NSString *path = [[NSBundle mainBundle] pathForResource:@"contactD" ofType:@"plist"];
    contacts_ = [[NSMutableArray alloc]initWithContentsOfFile:path];

//Filter array using predicates
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K CONTAINS[cd] %@", "ABC", selection];

//ALERT DISPLAYS HERE:
    contacts_ = [contacts_ filteredArrayUsingPredicate:predicate];

//Apply sorting on load
    NSSortDescriptor *contactSorter = [[NSSortDescriptor alloc] initWithKey:LAST_KEY ascending:YES selector:@selector(caseInsensitiveCompare:)];
    [contacts_ sortUsingDescriptors:[NSArray arrayWithObject:contactSorter]];

    [contactSorter release];  
}

帮助帮助!

谢谢! 布赖恩

1 个答案:

答案 0 :(得分:1)

出现警告是因为您实际上尝试将NSArray *分配给NSMutableArray ...

要解决此问题,请获取数组的可变副本,如下所示:

[[contacts_ filteredArrayUsingPredicate:predicate] mutableCopy];

但你仍然遇到内存问题,一个正确的方法是:

NSArray *tmp = [contacts_ filteredArrayUsingPredicate:predicate];
[contacts_ removeAllObjects];
[contacts_ addObjectsFromArray:tmp];