如何获取Core Data数据库的最后一条记录? [英] How do I get the last record of a Core Data database?
问题描述
我有一个名为images的核心数据实体,只有2个字段:
I have a core data entity called images that has just 2 fields:
imageName = NSString
timeStamp = NSNumber
我试图模拟一种堆栈LIFO(后进先出)。
插入新条目很容易,但是如何读取添加到实体的最后一个条目呢?
I am trying to simulate a kind of stack LIFO (last in first out). Inserting a new entry is easy but what about reading the last entry added to the entity?
所有图像都添加了时间戳, p>
All images are added with a timestamp, obtained by using
time_t unixTime = (time_t) [[NSDate date] timeIntervalSince1970];
等于自1970年以来的秒数的整数
an integer that is equal to the number of seconds since 1970
因此,如何检索核心数据的最后插入的记录(=具有最大时间戳记号的记录)
so, how do I retrieve the last inserted record of a core data (= the record that has the biggest timestamp number)???
谢谢
推荐答案
执行撷取要求,并按 timeStamp
/ p>
Perform a fetch request, sorting the results by timeStamp
.
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:...];
// Results should be in descending order of timeStamp.
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"timeStamp" ascending:NO];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSArray *results = [managedObjectContext executeFetchRequest:request error:NULL];
Entity *latestEntity = [results objectAtIndex:0];
您可能还想使用 NSFetchRequest
' setFetchLimit:
。
这篇关于如何获取Core Data数据库的最后一条记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!