Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kafran/d308416e5aa254134c4196099e533bcd to your computer and use it in GitHub Desktop.
Save kafran/d308416e5aa254134c4196099e533bcd to your computer and use it in GitHub Desktop.
[Auto increment in Core Data] How to implement auto-increment in core data while saving it #coredata
import Foundation
import CoreData
extension MyCoredataObject {
@nonobjc public class func createFetchRequest() -> NSFetchRequest<MyCoredataObject> {
return NSFetchRequest<MyCoredataObject>(entityName: "MyCoredataObject")
}
@NSManaged public var sortId: Int64
public override func willSave() {
super.willSave()
if self.sortId == 0 {
setPrimitiveValue(getAutoIncremenet(), forKey: "sortId")
}
}
func getAutoIncremenet() -> Int64 {
let url = self.objectID.uriRepresentation()
let urlString = url.absoluteString
if let pN = urlString.components(separatedBy: "/").last {
let numberPart = pN.replacingOccurrences(of: "p", with: "")
if let number = Int64(numberPart) {
return number
}
}
return 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment