0

我正在尝试从核心数据中检索最新的 NSdate 条目。我尝试这样做的方式是按日期排序并获取objectAtIndex. 但是,我正在努力检索结果并将其返回为nil. 我认为我的问题已经存在,NSDate *obj = [results objectAtIndex:0];但我不确定如何解决它。任何建议都将受到欢迎。我可能会过分,所以如果我是的话,请原谅我。

- (void)viewDidLoad
{
    [super viewDidLoad];
    //Get Reference to App Delegate
    SSAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    //Fetch Entity
    NSFetchRequest *request = [[NSFetchRequest alloc]
                              initWithEntityName:@"RecentDetails"];
    //Sort By Date
    NSSortDescriptor *sort = [[NSSortDescriptor alloc]initWithKey:@"date" ascending:NO];
    [request setSortDescriptors:[NSArray arrayWithObject:sort]];
    //Store In Array
     NSArray *results = [context executeFetchRequest:request error:NULL];

/////////////NEEDS EXTRA HERE ACCORDING TO COMMENTS


    //Find Object at Index 0
    NSDate *obj = [results objectAtIndex:0];
    //Set Batch Size
    [request setFetchBatchSize:1];

    //NSDate Formatter
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"ddMMyyyy"];

    //Convert to string
    NSString *stringFromDate = [dateFormatter stringFromDate:obj];

    //Test Log
    NSLog(@"Latest Date! %@", stringFromDate);

}
4

1 回答 1

1
  • 插入时,更改:

    NSManagedObjectContext *recentDetails = [NSEntityDescription insertNewObjectForEntityForName:@"RecentDetails"inManagedObjectContext:context];
    

    到:

    NSManagedObject *recentDetails = [NSEntityDescription insertNewObjectForEntityForName:@"RecentDetails"inManagedObjectContext:context];`
    
  • 检索时,就像 Stakenborg 指出的那样,您应该从“RecentDetails”的实体对象中获取日期属性。

  • [request setFetchBatchSize:1]应该在 之前设置[context executeFetchRequest:request...],否则对获取的RecentDetails 对象的数量没有影响。

于 2013-07-17T12:48:54.967 回答