【问题标题】:NSFetchRequest: fetch the object for which the predicate is trueNSFetchRequest:获取谓词为真的对象
【发布时间】:2011-06-27 20:35:52
【问题描述】:

我有以下提取。我想获取谓词为真的Session 对象。

我这样做对吗?我如何初始化/定义indexPath,因为它没有被识别。

NSDate * searchDate = [formatter dateFromString:dateString];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Session" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSPredicate * predicate1 = [NSPredicate predicateWithFormat:@" timeStamp == %@ ", searchDate];
[request setPredicate: predicate1];
[request setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSError *error = nil; 
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];

SessionViewController *sessionViewController = [[SessionViewController alloc] initWithNibName:@"SessionViewController" bundle:nil];
self.selectedSession = (Session *)[array objectAtIndexPath:indexPath];

sessionViewController.selectedSession = self.selectedSession;

[self.navigationController pushViewController:sessionViewController animated:YES];
[sessionViewController release];
[sortDescriptor release];
[request release];
[sortDescriptors release];

【问题讨论】:

    标签: ios objective-c cocoa-touch core-data nspredicate


    【解决方案1】:

    然后indexPath 变量通常由表视图delegate/datasource 回调提供。如果您使用的是UITableView,您提供的最后两行代码应放在以下方法之一中。

    - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
    - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
    

    其他行应该是让你的数据显示在表格视图中的方法。

    -(NSArray*)sessionData
    {
        if(!_sessionData)
        {
            //FetchRequest stuff
            NSError *error = nil; 
            _sessionData = [managedObjectContext executeFetchRequest:request error:&error];
            //Error checking/logging
        }
        return _sessionData;
    }
    

    现在下面的@"timeStamp == %@" 仅在时间戳是精确到毫秒的日期时才有效。如果这是您想要的,则使用日期范围 @" timeStamp >= %@ AND timeStamp

    注意:如果您发布了所有代码,则您在多个对象上缺少发布

    请求
    sortDescriptor
    sortDescriptors

    【讨论】:

    • 谢谢,Joe,我正在将此代码与 Calendar 一起使用,方法标题为 - (void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)d。我不太清楚如何正确使用此方法。
    • 一个日期可以进行多个会话吗?如果是这样,您如何显示多个会话。
    • 不,创建会话时,1 个日期的会话数不得超过 1 个。没有 2 个会话对象具有相同的日期。 (天)
    • 我错过了你的 cmets,现在一切都对你有用吗?哪个部分帮助修复了它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 2018-08-15
    • 1970-01-01
    相关资源
    最近更新 更多