【问题标题】:How can I sort and filter a plist data at once?如何一次对 plist 数据进行排序和过滤?
【发布时间】:2012-01-23 18:12:08
【问题描述】:

这里是 Objective-C 新手,

我正在尝试从 plist 中提取数据,对其进行过滤,然后进行排序。 我在其他页面上使用下面的排序方法,效果很好。

我确实在以下行中收到此警报: 从'NSArray *' 分配给'NSMutableArray *' 的指针类型不兼容

我收到此错误:

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

求助!

谢谢! 布赖恩

【问题讨论】:

    标签: objective-c sorting plist filtering


    【解决方案1】:

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

    要解决这个问题,请像这样获取数组的可变副本:

    [[contacts_ filteredArrayUsingPredicate:predicate] mutableCopy];
    

    但是你仍然有内存问题,正确的方法是:

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

    【讨论】:

    • 做到了!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多