如何使用CoreData检索列中最后插入的值? [英] How to retrieve the last inserted value in a column using CoreData?

查看:459
本文介绍了如何使用CoreData检索列中最后插入的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的CoreData应用程序中,我要显示学生中最后插入的 stdId 。是否有任何简单的方法来检索列中最后插入的值?

In my CoreData application I want display the last inserted stdId in Table Student. Is there any easy way to retrieve the last inserted value in a column ?

推荐答案

c> Student 实体您添加 NSDate 的属性,例如 createdAt

It's quite simple if in your Student entity you add a property of type NSDate like createdAt.

当您插入新的 Student 时,您需要传递该资源的当前日期。

When you insert a new Student, you need to pass the current date for that property.

[aStudent setValue:[NSDate date] forKey:@"createdAt"];

aStudent.createdAt = [NSDate date];



< 。

if you have created a subclass of Entity.

完成后,您可以使用限制1和一个排序描述符取值学生 code>

Once done, you can fetch against Student using a limit of 1 and a sort descriptor with ascending value NO.

NSFetchRequest* request = [NSFecthRequest fetchRequestWithEntityName:@"Student"];
[request setFetchLimit:1];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];

NSError *error;
NSArray *results = [context executeFetchRequest:request error:&error];

NSManagedObject *latestAddedStudent = [results objectAtIndex:0];

希望有帮助。

这篇关于如何使用CoreData检索列中最后插入的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆