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

IPhone IT屋
问 题

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 ?

解决方案

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

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

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

or

aStudent.createdAt = [NSDate date];

if you have created a subclass of Entity.

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

Hope that helps.

本文地址:IT屋 » How to retrieve the last inserted value in a column using CoreData?

问 题

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


解决方案

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



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



  [aStudent setValue:[NSDate date] forKey:@“createdAt”]; 




  aStudent.createdAt = [NSDate date];如果您已创建 Entity 的子类,则


<。



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



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


希望有帮助。


本文地址:IT屋 » 如何使用CoreData检索列中最后插入的值?