Get last inserted item from Core Data, iOS

Is there a way to get the last inserted item in the kernel database database?

+3
source share
3 answers

This returns the most recently inserted object.

setFetchLimit: 1 and setFetchOffset: [number of all entries - 1]

+3
source

I do not think this is supported by Core Data. I think your best bet is to add the dateInserted attribute to your entity.

0
source

1:
@Olsi , , . :

let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDelegate.managedObjectContext

let request = NSFetchRequest(entityName: "MyEntity")
let allElementsCount = context.countForFetchRequest(request, error: nil)
request.fetchLimit = 1
request.fetchOffset = allElementsCount - 1
request.returnsObjectsAsFaults = false

2:
Howerver sortDescriptors. , , :

let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDelegate.managedObjectContext

let request = NSFetchRequest(entityName: "MyEntity")
request.sortDescriptors = [NSSortDescriptor(key: "momentTimeStamp", ascending: false)]
request.fetchLimit = 1
request.returnsObjectsAsFaults = false
0

Source: https://habr.com/ru/post/1788704/


All Articles