【问题标题】:iPhone: Get indexPath of Predicate ObjectiPhone:获取谓词对象的 indexPath
【发布时间】:2010-05-28 01:33:00
【问题描述】:

我正在使用谓词在核心数据中查找对象。我可以成功找到我想要的对象,但我还需要获取该对象的 indexPath,以便我可以推送该对象的详细信息视图。目前我有以下代码来获取我的对象:

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Ride" inManagedObjectContext:self.managedObjectContext]];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title = %@ AND addressFull = %@", view.annotation.title, view.annotation.subtitle];
    [fetchRequest setPredicate:predicate];
    NSMutableArray *sortDescriptors = [NSMutableArray array];
    [sortDescriptors addObject:[[[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES] autorelease]];
    [sortDescriptors addObject:[[[NSSortDescriptor alloc] initWithKey:@"addressFull" ascending:YES] autorelease]];
    [fetchRequest setSortDescriptors:sortDescriptors];
    [fetchRequest setReturnsObjectsAsFaults:NO];
    [fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"title", @"addressFull", nil]];
    NSError *error = nil;
    NSArray *fetchedItems = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    // Sohow what record we returned
    NSLog(@"%@",[fetchedItems objectAtIndex:0]);

所以,我可以正确地将我的对象放入一个数组中。 但是如何将该对象转换为 indexPath?

【问题讨论】:

    标签: iphone core-data predicate nsfetchrequest


    【解决方案1】:

    索引路径只是一组索引,例如{0, 2} 可能表示指向表视图的第一部分和第三行的索引路径——假设您的数组数据的表视图表示是您的最终目标。

    该索引路径可以指向数组中的任何特定对象,具体取决于您将路径转换为数组索引的方式。

    如果你想创建一个任意的索引路径,这很容易:

    NSUInteger myFirstIndex = 0;
    NSUInteger mySecondIndex = 2;
    NSUInteger myIndices[] = {myFirstIndex, mySecondIndex};
    NSIndexPath *myIndexPath = [[NSIndexPath alloc] initWithIndexes:myIndices length:2];
    // ...do someting with myIndexPath...
    [myIndexPath release];
    

    因此,您需要做的是弄清楚您的数组结构如何转换为部分和行(再次假设您要制作表格视图表示)。

    另一种选择是使用NSFetchedResultsController 为您处理表视图更新——它将为您处理索引路径,具体取决于您对部分进行分区的方式。

    【讨论】:

    • 是的,你是对的,我想在 UITableView 中显示它。只是想在被点击的地图注释的详细信息视图中滑动。
    • 我建议您将数据提取放入NSFetchedResultsController 并让它进行表格视图更新。它消除了大约 99% 的将 Core Data 提取结果连接到表视图的工作。
    • 我得到了它的工作,只需要用我的根控制器初始化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多