I am having a bit of trouble figuring out this Core Data stuff. How do I create a new entry with a unique ID? In SQL I would just declare one field as an autoincrement fie
This class function will return next available number for your id property (it must be integer property).
I call it auto-increment value generator. I still agree with others that there is objectID for that but sometimes you just need number.
You can put this function in your NSManagedObject subclass for the entity:
+(NSNumber *)nextAvailble:(NSString *)idKey forEntityName:(NSString *)entityName inContext:(NSManagedObjectContext *)context{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSManagedObjectContext *moc = context;
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:moc];
[request setEntity:entity];
// [request setFetchLimit:1];
NSArray *propertiesArray = [[NSArray alloc] initWithObjects:idKey, nil];
[request setPropertiesToFetch:propertiesArray];
[propertiesArray release], propertiesArray = nil;
NSSortDescriptor *indexSort = [[NSSortDescriptor alloc] initWithKey:idKey ascending:YES];
NSArray *array = [[NSArray alloc] initWithObjects:indexSort, nil];
[request setSortDescriptors:array];
[array release], array = nil;
[indexSort release], indexSort = nil;
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
// NSSLog(@"Autoincrement fetch results: %@", results);
NSManagedObject *maxIndexedObject = [results lastObject];
[request release], request = nil;
if (error) {
NSLog(@"Error fetching index: %@\n%@", [error localizedDescription], [error userInfo]);
}
//NSAssert3(error == nil, @"Error fetching index: %@\n%@", [error localizedDescription], [error userInfo]);
NSInteger myIndex = 1;
if (maxIndexedObject) {
myIndex = [[maxIndexedObject valueForKey:idKey] integerValue] + 1;
}
return [NSNumber numberWithInteger:myIndex];
}
Swift 5.0
func nextAvailble(_ idKey: String, forEntityName entityName: String, in context: NSManagedObjectContext) -> NSNumber? {
let req = NSFetchRequest.init(entityName: entityName)
let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
req.entity = entity
req.fetchLimit = 1
req.propertiesToFetch = [idKey]
let indexSort = NSSortDescriptor.init(key: idKey, ascending: false)
req.sortDescriptors = [indexSort]
do {
let fetchedData = try context.fetch(req)
let firstObject = fetchedData.first as! NSManagedObject
if let foundValue = firstObject.value(forKey: idKey) as? NSNumber {
return NSNumber.init(value: foundValue.intValue + 1)
}
} catch {
print(error)
}
return nil
}