如何在Xcode中从过滤后的数组创建表视图控制器?

时间:2014-03-10 19:35:47

标签: ios objective-c cocoa-touch uipageviewcontroller

目前我有2张表格。一个是显示每个单元格的基本单元,如果选择它,它将导航到一个详细视图控制器。

我创建了一个新的ViewController来创建一个过滤的页面视图。我用plist填充我的页面视图。我设法创建了一个过滤器,但我不知道如何从这里开始。

这是我的代码:

- (IBAction)ingredientsAddButton:(UIButton *)sender 
{
    int j=0;
    onemsiz.text=ingredientTextField.text;
    ingredientText=onemsiz.text;
    NSLog(ingredientText);
    NSString *path = [[NSBundle mainBundle] pathForResource:@"recipes" ofType:@"plist"];
    NSArray *arrayOfPlist = [[NSArray alloc] initWithContentsOfFile:path];
    if (arrayOfPlist==NULL) {

    }else {
        for (int i=0; i<4; i++) { 
            // i currently have 4 element is plist.
            NSString *strCurrentRecipeIngredients = [[arrayOfPlist objectAtIndex:i] objectForKey:@"recipeIngredients"];
            NSString *strCurrentRecipeName = [[arrayOfPlist objectAtIndex:i] objectForKey:@"recipeName"];
            //NSLog(@"%d. Loop \n", i+1);
            if([strCurrentRecipeIngredients rangeOfString:(@"%@",ingredientText)].location!=NSNotFound)
            {
                NSLog(@"%@ contains %@ ",strCurrentRecipeName, ingredientText);
                NSLog(ingredientText);
                NSLog(strCurrentRecipeIngredients);
                j++;
            }else {
                NSLog(@"Not found");
                NSLog(ingredientText);
                NSLog(strCurrentRecipeIngredients);
            }
            if (ingredientText==NULL) {
                NSLog(@"empty input");
            }else {

            }
        }
    }
    NSLog(@"%d",j);
}

我的第一个问题是如何在表格视图中显示结果?如果你愿意,我可以提供一些截图。

1 个答案:

答案 0 :(得分:0)

您可以添加bool ivar,它将告知您何时需要显示已过滤的数组以及将显示已过滤数据的新数组:

BOOL isShowFilteredData;
NSArray *filteredData;

在init或viewDidLoad中将bool初始化为false(您不想显示所有数据);

isShowFilteredData = NO;

您必须更改数据源/委托方法才能使用正确的数据:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return isShowFilteredData ? isShowFilteredData.count : myDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //configure cell, etc..
    //your code 
    if (isShowFilteredData) 
    {
         // show filtered data
         id obj = filteredData[indexPath.row];
         // do something with result
    }
    else
    {
        // show all data
    }
}

现在,当您想要显示已过滤的数据时,只需将ivar更改为true,初始化filteredData数组并使用您要显示的数据填充它并调用reloadData:

isShowFilteredData = YES;
filteredData = [[NSArray alloc] initWithObjects:.....];
[self.tableView reloadData];

但是如果你想显示所有数据:

isShowFilteredData = NO;
[self.tableView reloadData];

这只是您可以使用的解决方案之一。