从 plist 中只获取某些字符串 iOS

Get only certain Strings from plist iOS

我有一个 plist,我只想抓取 'Name' 字符串以 'A' 开头的项目。然后我想在我的 UITableView 中显示这些,以及项目中包含的 'NameOrigin'。我已经包含了我的 plist 的屏幕截图。谢谢

我的代码到目前为止,我能够显示所有 plist 项目,但我想过滤显示的项目为字符串 'Name' 带有字母 'A' 的项目?

-(NSArray *)content
{
    //if (!_content) {
    _content = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"MyPLIST" ofType:@"plist"]];
    // }
    return _content;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [TableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    cell.textLabel.text = [[self.content objectAtIndex:indexPath.row] objectForKey:@"Name"];
    cell.detailTextLabel.text = [[self.content objectAtIndex:indexPath.row] valueForKey:@"NameOrigin"];

    return cell;
}

如果您只想过滤 Name 以 "A" 开头的元素,试试这个:

NSArray *filteredArray = [self.content filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"Name beginswith %@", @"A"]];

就此而言:您应该考虑稍微重构一下您的代码。每次 调用 [self content] 时从文件 重新加载数据是一个 糟糕的 想法,性能明智。试试这个:

// Create a property called content in your class extension on the top of the .m file of your table view controller
@interface YourTableViewController ()
@property (nonatomic, strong) NSArray *content;
@end

接下来,在您的 viewDidLoad 回调中添加此代码:

_content = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"MyPLIST" ofType:@"plist"]];

并删除自定义 content 方法。