extensionMovie { @nonobjcpublicclassfuncfetchRequest() -> NSFetchRequest<Movie> { returnNsFetchReauest<Movie>(entityName: "Movie") } // We can make this not optional by simply deleting question mark @NSManagedpublicvar title: String? @NSManagedpublicvar director: String @NSManagedpublicvar year: Int16 // In case of nil collapsing, we can add publicvar wrappedTitle:String { title ??"Unknown Title" } }
extensionMovie :Identifiable { }
Core data only load data when is actually needed (lazy load). This is good.
L3: Conditional saving of NSManagedObjectContext
1 2 3 4 5 6 7 8 9 10 11
structContentView: View { @Environment(\. managedobjectContext) var moc var body:someView { Button("Save"){ // moc.hasChanges help us be sure about saving data only when changed if moc.hasChanges { try? moc.save() } } } }
L4: Ensuring Core Data objects are unique using constraints
To make sure some specific attributes have unique values, add attribute name to Constraints in the right column.
// Find all data whose inital character is before F in alphabet @FetchRequest(sortDescriptors: [], predicate: NSPredicate(format:"universe < %@ ", "F")) var ships: FetchedResults<Ship>
// IN @FetchRequest(sortDescriptors: [], predicate: NSPredicate(format:"universe IN %@ ", ["Aliens","Firefly"])) var ships: FetchedResults<Ship>
// BEGINSWITH is Case sensitive, while BEGINSWITH[c] is not @FetchRequest(sortDescriptors: [], predicate: NSPredicate(format:"name BEGINSWITH %@ ", "E")) var ships: FetchedResults<Ship> @FetchRequest(sortDescriptors: [], predicate: NSPredicate(format:"name BEGINSWITH %@ ", "e")) var ships: FetchedResults<Ship> @FetchRequest(sortDescriptors: [], predicate: NSPredicate(format:"name BEGINSWITH[c] %@ ", "e")) var ships: FetchedResults<Ship>
// Core Data files extensionCountry{ // Omit some codes here // shortName must be unique in order to specify the relationship @NSManagedpublicvar shortName:String? @NSManagedpublicvar candy: NSSet? publicvar candyArray: [Candy]{ letset= candy as?Set<Candy> ?? [] returnset.sorted{ // Remember to declare `wrappedName` in `Candy` $0.wrappedName <$1.wrappedName } } }