Last active
December 5, 2022 23:10
-
-
Save novinfard/0431755c356623a943f477c13e5c835a 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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