开发者

NSFetchRequest: fetch the object for which the predicate is true

I have the following fetch. I want to fetch the Session object for whic开发者_JS百科h the predicate is true.

Am I doing this right? And how can I init/define indexPath, because it is not being recognized.

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


Then indexPath variable is usually supplied from a tableview delegate/datasource callback. The last two lines of code you provided should be placed in one of the following methods if you are using a UITableView.

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

The other lines should be in a method to get your data to display in the tableview.

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

Now the following @" timeStamp == %@ " will only work if the timestamp is that EXACT date to the millisecond. If this is what you want great, otherwise use a date range @" timeStamp >= %@ AND timeStamp <= %@ ".

Note: Your missing releases on several objects if you posted all of your code

request
sortDescriptor
sortDescriptors

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜