gpt4 book ai didi

ios - 从核心数据中检索 NSDate

转载 作者:行者123 更新时间:2023-11-29 03:46:27 24 4
gpt4 key购买 nike

我正在尝试从核心数据中检索最新的 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);

}

最佳答案

  • 插入时,更改:

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

    到:

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

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

关于ios - 从核心数据中检索 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17698781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com