CoreStore
public enum CoreStore
CoreStore is the main entry point for all other APIs.
-
The default
DataStackinstance to be used. IfdefaultStackis not set before the first time accessed, a default-configuredDataStackwill be created.See also
DataStackNote
Changing thedefaultStackis thread safe, but it is recommended to setupDataStackson a common queue (e.g. the main queue).Declaration
Swift
public static var defaultStack: DataStack { get set }
-
The
CoreStoreLoggerinstance to be used. The default logger is an instance of aDefaultLogger.Declaration
Swift
public static var logger: CoreStoreLogger
-
Asynchronously adds a
StorageInterfaceto thedefaultStack. Migrations are also initiated by default.CoreStore.addStorage( InMemoryStore(configuration: "Config1"), completion: { result in switch result { case .success(let storage): // ... case .failure(let error): // ... } } )Declaration
Swift
public static func addStorage<T>(_ storage: T, completion: @escaping (SetupResult<T>) -> Void)Parameters
storagethe storage
completionthe closure to be executed on the main queue when the process completes, either due to success or failure. The closure’s
SetupResultargument indicates the result. Note that theStorageInterfaceassociated to theSetupResult.successmay not always be the same instance as the parameter argument if a previousStorageInterfacewas already added at the same URL and with the same configuration. -
Asynchronously adds a
LocalStorageto thedefaultStack. Migrations are also initiated by default.let migrationProgress = CoreStore.addStorage( SQLiteStore(fileName: "core_data.sqlite", configuration: "Config1"), completion: { result in switch result { case .success(let storage): // ... case .failure(let error): // ... } } )Declaration
Swift
public static func addStorage<T: LocalStorage>(_ storage: T, completion: @escaping (SetupResult<T>) -> Void) -> Progress?Parameters
storagethe local storage
completionthe closure to be executed on the main queue when the process completes, either due to success or failure. The closure’s
SetupResultargument indicates the result. Note that theLocalStorageassociated to theSetupResult.successmay not always be the same instance as the parameter argument if a previousLocalStoragewas already added at the same URL and with the same configuration.Return Value
a
Progressinstance if a migration has started, ornilif either no migrations are required or if a failure occured. -
Asynchronously adds a
CloudStorageto thedefaultStack. Migrations are also initiated by default.guard let storage = ICloudStore( ubiquitousContentName: "MyAppCloudData", ubiquitousContentTransactionLogsSubdirectory: "logs/config1", ubiquitousContainerID: "iCloud.com.mycompany.myapp.containername", ubiquitousPeerToken: "9614d658014f4151a95d8048fb717cf0", configuration: "Config1", cloudStorageOptions: .recreateLocalStoreOnModelMismatch ) else { // iCloud is not available on the device return } let migrationProgress = dataStack.addStorage( storage, completion: { result in switch result { case .success(let storage): // ... case .failure(let error): // ... } } )Declaration
Swift
public static func addStorage<T: CloudStorage>(_ storage: T, completion: @escaping (SetupResult<T>) -> Void)Parameters
storagethe cloud storage
completionthe closure to be executed on the main queue when the process completes, either due to success or failure. The closure’s
SetupResultargument indicates the result. Note that theCloudStorageassociated to theSetupResult.successmay not always be the same instance as the parameter argument if a previousCloudStoragewas already added at the same URL and with the same configuration. -
Migrates a local storage to match the
defaultStack‘s managed object model version. This method does NOT add the migrated store to the data stack.Throws
aCoreStoreErrorvalue indicating the failureDeclaration
Swift
public static func upgradeStorageIfNeeded<T: LocalStorage>(_ storage: T, completion: @escaping (MigrationResult) -> Void) throws -> Progress?Parameters
storagethe local storage
completionthe closure to be executed on the main queue when the migration completes, either due to success or failure. The closure’s
MigrationResultargument indicates the result. This closure is NOT executed if an error is thrown, but will be executed with a.failureresult if an error occurs asynchronously.Return Value
a
Progressinstance if a migration has started, ornilis no migrations are required -
Checks the migration steps required for the storage to match the
defaultStack‘s managed object model version.Throws
aCoreStoreErrorvalue indicating the failureDeclaration
Swift
public static func requiredMigrationsForStorage<T>(_ storage: T) throws -> [MigrationType] where T : LocalStorageParameters
storagethe local storage
Return Value
a
MigrationTypearray indicating the migration steps required for the store, or an empty array if the file does not exist yet. Otherwise, an error is thrown if either inspection of the store failed, or if no mapping model was found/inferred.
-
Using the
defaultStack, creates anObjectMonitorfor the specifiedDynamicObject. MultipleObjectObservers may then register themselves to be notified when changes are made to theDynamicObject.Declaration
Swift
public static func monitorObject<D>(_ object: D) -> ObjectMonitor<D> where D : DynamicObjectParameters
objectthe
DynamicObjectto observe changes fromReturn Value
a
ObjectMonitorthat monitors changes toobject -
Using the
defaultStack, creates aListMonitorfor a list ofDynamicObjects that satisfy the specified fetch clauses. MultipleListObservers may then register themselves to be notified when changes are made to the list.Declaration
Swift
public static func monitorList<D>(_ from: From<D>, _ fetchClauses: FetchClause...) -> ListMonitor<D> where D : DynamicObjectParameters
froma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for fetching the object list. AcceptsWhere,OrderBy, andTweakclauses.Return Value
a
ListMonitorinstance that monitors changes to the list -
Using the
defaultStack, creates aListMonitorfor a list ofDynamicObjects that satisfy the specified fetch clauses. MultipleListObservers may then register themselves to be notified when changes are made to the list.Declaration
Swift
public static func monitorList<D>(_ from: From<D>, _ fetchClauses: [FetchClause]) -> ListMonitor<D> where D : DynamicObjectParameters
froma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for fetching the object list. AcceptsWhere,OrderBy, andTweakclauses.Return Value
a
ListMonitorinstance that monitors changes to the list -
Creates a
ListMonitorfor a list ofDynamicObjects that satisfy the specifiedFetchChainableBuilderTypebuilt from a chain of clauses.let monitor = CoreStore.monitorList( From<MyPersonEntity>() .where(\.age > 18) .orderBy(.ascending(\.age)) )Declaration
Swift
public static func monitorList<B>(_ clauseChain: B) -> ListMonitor<B.ObjectType> where B : FetchChainableBuilderTypeParameters
clauseChaina
FetchChainableBuilderTypebuilt from a chain of clausesReturn Value
a
ListMonitorfor a list ofDynamicObjects that satisfy the specifiedFetchChainableBuilderType -
Using the
defaultStack, asynchronously creates aListMonitorfor a list ofDynamicObjects that satisfy the specified fetch clauses. MultipleListObservers may then register themselves to be notified when changes are made to the list. SinceNSFetchedResultsControllergreedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed.Declaration
Swift
public static func monitorList<D>(createAsynchronously: @escaping (ListMonitor<D>) -> Void, _ from: From<D>, _ fetchClauses: FetchClause...)Parameters
createAsynchronouslythe closure that receives the created
ListMonitorinstancefroma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for fetching the object list. AcceptsWhere,OrderBy, andTweakclauses. -
Using the
defaultStack, asynchronously creates aListMonitorfor a list ofDynamicObjects that satisfy the specified fetch clauses. MultipleListObservers may then register themselves to be notified when changes are made to the list. SinceNSFetchedResultsControllergreedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed.Declaration
Swift
public static func monitorList<D>(createAsynchronously: @escaping (ListMonitor<D>) -> Void, _ from: From<D>, _ fetchClauses: [FetchClause])Parameters
createAsynchronouslythe closure that receives the created
ListMonitorinstancefroma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for fetching the object list. AcceptsWhere,OrderBy, andTweakclauses. -
Asynchronously creates a
ListMonitorfor a list ofDynamicObjects that satisfy the specifiedFetchChainableBuilderTypebuilt from a chain of clauses. SinceNSFetchedResultsControllergreedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed.CoreStore.monitorList( createAsynchronously: { (monitor) in self.monitor = monitor }, From<MyPersonEntity>() .where(\.age > 18) .orderBy(.ascending(\.age)) )Declaration
Swift
public static func monitorList<B: FetchChainableBuilderType>(createAsynchronously: @escaping (ListMonitor<B.ObjectType>) -> Void, _ clauseChain: B)Parameters
createAsynchronouslythe closure that receives the created
ListMonitorinstanceclauseChaina
FetchChainableBuilderTypebuilt from a chain of clauses -
Using the
defaultStack, creates aListMonitorfor a sectioned list ofDynamicObjects that satisfy the specified fetch clauses. MultipleListObservers may then register themselves to be notified when changes are made to the list.Declaration
Swift
public static func monitorSectionedList<D>(_ from: From<D>, _ sectionBy: SectionBy<D>, _ fetchClauses: FetchClause...) -> ListMonitor<D> where D : DynamicObjectParameters
froma
Fromclause indicating the entity typesectionBya
SectionByclause indicating the keyPath for the attribute to use when sorting the list into sections.fetchClausesa series of
FetchClauseinstances for fetching the object list. AcceptsWhere,OrderBy, andTweakclauses.Return Value
a
ListMonitorinstance that monitors changes to the list -
Using the
defaultStack, creates aListMonitorfor a sectioned list ofDynamicObjects that satisfy the specified fetch clauses. MultipleListObservers may then register themselves to be notified when changes are made to the list.Declaration
Swift
public static func monitorSectionedList<D>(_ from: From<D>, _ sectionBy: SectionBy<D>, _ fetchClauses: [FetchClause]) -> ListMonitor<D> where D : DynamicObjectParameters
froma
Fromclause indicating the entity typesectionBya
SectionByclause indicating the keyPath for the attribute to use when sorting the list into sections.fetchClausesa series of
FetchClauseinstances for fetching the object list. AcceptsWhere,OrderBy, andTweakclauses.Return Value
a
ListMonitorinstance that monitors changes to the list -
Creates a
ListMonitorfor a sectioned list ofDynamicObjects that satisfy the specifiedSectionMonitorBuilderTypebuilt from a chain of clauses.let monitor = CoreStore.monitorSectionedList( From<MyPersonEntity>() .sectionBy(\.age, { "\($0!) years old" }) .where(\.age > 18) .orderBy(.ascending(\.age)) )Declaration
Swift
public static func monitorSectionedList<B>(_ clauseChain: B) -> ListMonitor<B.ObjectType> where B : SectionMonitorBuilderTypeParameters
clauseChaina
SectionMonitorBuilderTypebuilt from a chain of clausesReturn Value
a
ListMonitorfor a list ofDynamicObjects that satisfy the specifiedSectionMonitorBuilderType -
Using the
defaultStack, asynchronously creates aListMonitorfor a sectioned list ofDynamicObjects that satisfy the specified fetch clauses. MultipleListObservers may then register themselves to be notified when changes are made to the list. SinceNSFetchedResultsControllergreedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed.Declaration
Swift
public static func monitorSectionedList<D>(createAsynchronously: @escaping (ListMonitor<D>) -> Void, _ from: From<D>, _ sectionBy: SectionBy<D>, _ fetchClauses: FetchClause...)Parameters
createAsynchronouslythe closure that receives the created
ListMonitorinstancefroma
Fromclause indicating the entity typesectionBya
SectionByclause indicating the keyPath for the attribute to use when sorting the list into sections.fetchClausesa series of
FetchClauseinstances for fetching the object list. AcceptsWhere,OrderBy, andTweakclauses. -
Using the
defaultStack, asynchronously creates aListMonitorfor a sectioned list ofDynamicObjects that satisfy the specified fetch clauses. MultipleListObservers may then register themselves to be notified when changes are made to the list. SinceNSFetchedResultsControllergreedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed.Declaration
Swift
public static func monitorSectionedList<D>(createAsynchronously: @escaping (ListMonitor<D>) -> Void, _ from: From<D>, _ sectionBy: SectionBy<D>, _ fetchClauses: [FetchClause])Parameters
createAsynchronouslythe closure that receives the created
ListMonitorinstancefroma
Fromclause indicating the entity typesectionBya
SectionByclause indicating the keyPath for the attribute to use when sorting the list into sections.fetchClausesa series of
FetchClauseinstances for fetching the object list. AcceptsWhere,OrderBy, andTweakclauses. -
Asynchronously creates a
ListMonitorfor a sectioned list ofDynamicObjects that satisfy the specifiedSectionMonitorBuilderTypebuilt from a chain of clauses.CoreStore.monitorSectionedList( createAsynchronously: { (monitor) in self.monitor = monitor }, From<MyPersonEntity>() .sectionBy(\.age, { "\($0!) years old" }) .where(\.age > 18) .orderBy(.ascending(\.age)) )Declaration
Swift
public static func monitorSectionedList<B: SectionMonitorBuilderType>(createAsynchronously: @escaping (ListMonitor<B.ObjectType>) -> Void, _ clauseChain: B)Parameters
createAsynchronouslythe closure that receives the created
ListMonitorinstanceclauseChaina
SectionMonitorBuilderTypebuilt from a chain of clauses
-
Using the
defaultStack, fetches theDynamicObjectinstance in theDataStack‘s context from a reference created from a transaction or from a different managed object context.Declaration
Swift
public static func fetchExisting<D>(_ object: D) -> D? where D : DynamicObjectParameters
objecta reference to the object created/fetched outside the
DataStackReturn Value
the
DynamicObjectinstance if the object exists in theDataStack, ornilif not found. -
Using the
defaultStack, fetches theDynamicObjectinstance in theDataStack‘s context from anNSManagedObjectID.Declaration
Swift
public static func fetchExisting<D>(_ objectID: NSManagedObjectID) -> D? where D : DynamicObjectParameters
objectIDthe
NSManagedObjectIDfor the objectReturn Value
the
DynamicObjectinstance if the object exists in theDataStack, ornilif not found. -
Using the
defaultStack, fetches theDynamicObjectinstances in theDataStack‘s context from references created from a transaction or from a different managed object context.Declaration
Swift
public static func fetchExisting<D, S>(_ objects: S) -> [D] where D : DynamicObject, D == S.Element, S : SequenceParameters
objectsan array of
DynamicObjects created/fetched outside theDataStackReturn Value
the
DynamicObjectarray for objects that exists in theDataStack -
Using the
defaultStack, fetches theDynamicObjectinstances in theDataStack‘s context from a list ofNSManagedObjectID.Declaration
Swift
public static func fetchExisting<D, S>(_ objectIDs: S) -> [D] where D : DynamicObject, S : Sequence, S.Element == NSManagedObjectIDParameters
objectIDsthe
NSManagedObjectIDarray for the objectsReturn Value
the
DynamicObjectarray for objects that exists in theDataStack -
Using the
defaultStack, fetches the firstDynamicObjectinstance that satisfies the specifiedFetchClauses. AcceptsWhere,OrderBy, andTweakclauses.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchOne<D>(_ from: From<D>, _ fetchClauses: FetchClause...) throws -> D? where D : DynamicObjectParameters
froma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for the fetch request. AcceptsWhere,OrderBy, andTweakclauses.Return Value
the first
DynamicObjectinstance that satisfies the specifiedFetchClauses, ornilif no match was found -
Using the
defaultStack, fetches the firstDynamicObjectinstance that satisfies the specifiedFetchClauses. AcceptsWhere,OrderBy, andTweakclauses.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchOne<D>(_ from: From<D>, _ fetchClauses: [FetchClause]) throws -> D? where D : DynamicObjectParameters
froma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for the fetch request. AcceptsWhere,OrderBy, andTweakclauses.Return Value
the first
DynamicObjectinstance that satisfies the specifiedFetchClauses, ornilif no match was found -
Fetches the first
DynamicObjectinstance that satisfies the specifiedFetchChainableBuilderTypebuilt from a chain of clauses.let youngestTeen = CoreStore.fetchOne( From<MyPersonEntity>() .where(\.age > 18) .orderBy(.ascending(\.age)) )Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchOne<B>(_ clauseChain: B) throws -> B.ObjectType? where B : FetchChainableBuilderTypeParameters
clauseChaina
FetchChainableBuilderTypebuilt from a chain of clausesReturn Value
the first
DynamicObjectinstance that satisfies the specifiedFetchChainableBuilderType, ornilif no match was found -
Using the
defaultStack, fetches allDynamicObjectinstances that satisfy the specifiedFetchClauses. AcceptsWhere,OrderBy, andTweakclauses.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchAll<D>(_ from: From<D>, _ fetchClauses: FetchClause...) throws -> [D] where D : DynamicObjectParameters
froma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for the fetch request. AcceptsWhere,OrderBy, andTweakclauses.Return Value
all
DynamicObjectinstances that satisfy the specifiedFetchClauses, or an empty array if no match was found -
Using the
defaultStack, fetches allDynamicObjectinstances that satisfy the specifiedFetchClauses. AcceptsWhere,OrderBy, andTweakclauses.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchAll<D>(_ from: From<D>, _ fetchClauses: [FetchClause]) throws -> [D] where D : DynamicObjectParameters
froma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for the fetch request. AcceptsWhere,OrderBy, andTweakclauses.Return Value
all
DynamicObjectinstances that satisfy the specifiedFetchClauses, or an empty array if no match was found -
Fetches all
DynamicObjectinstances that satisfy the specifiedFetchChainableBuilderTypebuilt from a chain of clauses.let people = CoreStore.fetchAll( From<MyPersonEntity>() .where(\.age > 18) .orderBy(.ascending(\.age)) )Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchAll<B>(_ clauseChain: B) throws -> [B.ObjectType] where B : FetchChainableBuilderTypeParameters
clauseChaina
FetchChainableBuilderTypebuilt from a chain of clausesReturn Value
all
DynamicObjectinstances that satisfy the specifiedFetchChainableBuilderType, or an empty array if no match was found -
Using the
defaultStack, fetches the number ofDynamicObjects that satisfy the specifiedFetchClauses. AcceptsWhere,OrderBy, andTweakclauses.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchCount<D>(_ from: From<D>, _ fetchClauses: FetchClause...) throws -> Int where D : DynamicObjectParameters
froma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for the fetch request. AcceptsWhere,OrderBy, andTweakclauses.Return Value
the number of
DynamicObjects that satisfy the specifiedFetchClauses -
Using the
defaultStack, fetches the number ofDynamicObjects that satisfy the specifiedFetchClauses. AcceptsWhere,OrderBy, andTweakclauses.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchCount<D>(_ from: From<D>, _ fetchClauses: [FetchClause]) throws -> Int where D : DynamicObjectParameters
froma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for the fetch request. AcceptsWhere,OrderBy, andTweakclauses.Return Value
the number of
DynamicObjects that satisfy the specifiedFetchClauses -
Fetches the number of
DynamicObjects that satisfy the specifiedFetchChainableBuilderTypebuilt from a chain of clauses.let numberOfAdults = CoreStore.fetchCount( From<MyPersonEntity>() .where(\.age > 18) .orderBy(.ascending(\.age)) )Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchCount<B>(_ clauseChain: B) throws -> Int where B : FetchChainableBuilderTypeParameters
clauseChaina
FetchChainableBuilderTypebuilt from a chain of clausesReturn Value
the number of
DynamicObjects that satisfy the specifiedFetchChainableBuilderType -
Using the
defaultStack, fetches theNSManagedObjectIDfor the firstDynamicObjectthat satisfies the specifiedFetchClauses. AcceptsWhere,OrderBy, andTweakclauses.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchObjectID<D>(_ from: From<D>, _ fetchClauses: FetchClause...) throws -> NSManagedObjectID? where D : DynamicObjectParameters
froma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for the fetch request. AcceptsWhere,OrderBy, andTweakclauses.Return Value
the
NSManagedObjectIDfor the firstDynamicObjectthat satisfies the specifiedFetchClauses, ornilif no match was found -
Using the
defaultStack, fetches theNSManagedObjectIDfor the firstDynamicObjectthat satisfies the specifiedFetchClauses. AcceptsWhere,OrderBy, andTweakclauses.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchObjectID<D>(_ from: From<D>, _ fetchClauses: [FetchClause]) throws -> NSManagedObjectID? where D : DynamicObjectParameters
froma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for the fetch request. AcceptsWhere,OrderBy, andTweakclauses.Return Value
the
NSManagedObjectIDfor the firstDynamicObjectthat satisfies the specifiedFetchClauses, ornilif no match was found -
Fetches the
NSManagedObjectIDfor the firstDynamicObjectthat satisfies the specifiedFetchChainableBuilderTypebuilt from a chain of clauses.let youngestTeenID = CoreStore.fetchObjectID( From<MyPersonEntity>() .where(\.age > 18) .orderBy(.ascending(\.age)) )Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchObjectID<B>(_ clauseChain: B) throws -> NSManagedObjectID? where B : FetchChainableBuilderTypeParameters
clauseChaina
FetchChainableBuilderTypebuilt from a chain of clausesReturn Value
the
NSManagedObjectIDfor the firstDynamicObjectthat satisfies the specifiedFetchChainableBuilderType, ornilif no match was found -
Using the
defaultStack, fetches theNSManagedObjectIDfor allDynamicObjects that satisfy the specifiedFetchClauses. AcceptsWhere,OrderBy, andTweakclauses.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchObjectIDs<D>(_ from: From<D>, _ fetchClauses: FetchClause...) throws -> [NSManagedObjectID] where D : DynamicObjectParameters
froma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for the fetch request. AcceptsWhere,OrderBy, andTweakclauses.Return Value
the
NSManagedObjectIDfor allDynamicObjects that satisfy the specifiedFetchClauses, or an empty array if no match was found -
Using the
defaultStack, fetches theNSManagedObjectIDfor allDynamicObjects that satisfy the specifiedFetchClauses. AcceptsWhere,OrderBy, andTweakclauses.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchObjectIDs<D>(_ from: From<D>, _ fetchClauses: [FetchClause]) throws -> [NSManagedObjectID] where D : DynamicObjectParameters
froma
Fromclause indicating the entity typefetchClausesa series of
FetchClauseinstances for the fetch request. AcceptsWhere,OrderBy, andTweakclauses.Return Value
the
NSManagedObjectIDfor allDynamicObjects that satisfy the specifiedFetchClauses, or an empty array if no match was found -
Fetches the
NSManagedObjectIDfor allDynamicObjects that satisfy the specifiedFetchChainableBuilderTypebuilt from a chain of clauses.let idsOfAdults = transaction.fetchObjectIDs( From<MyPersonEntity>() .where(\.age > 18) .orderBy(.ascending(\.age)) )Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func fetchObjectIDs<B>(_ clauseChain: B) throws -> [NSManagedObjectID] where B : FetchChainableBuilderTypeParameters
clauseChaina
FetchChainableBuilderTypebuilt from a chain of clausesReturn Value
the
NSManagedObjectIDfor allDynamicObjects that satisfy the specifiedFetchChainableBuilderType, or an empty array if no match was found -
Using the
defaultStack, queries aggregate values as specified by theQueryClauses. Requires at least aSelectclause, and optionalWhere,OrderBy,GroupBy, andTweakclauses.A
query
differs from afetch
in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func queryValue<D, U>(_ from: From<D>, _ selectClause: Select<D, U>, _ queryClauses: QueryClause...) throws -> U? where D : DynamicObject, U : QueryableAttributeTypeParameters
froma
Fromclause indicating the entity typeselectClausea
Select<U>clause indicating the properties to fetch, and with the generic type indicating the return type.queryClausesa series of
QueryClauseinstances for the query request. AcceptsWhere,OrderBy,GroupBy, andTweakclauses.Return Value
the result of the the query, or
nilif no match was found. The type of the return value is specified by the generic type of theSelect<U>parameter. -
Using the
defaultStack, queries aggregate values as specified by theQueryClauses. Requires at least aSelectclause, and optionalWhere,OrderBy,GroupBy, andTweakclauses.A
query
differs from afetch
in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func queryValue<D, U>(_ from: From<D>, _ selectClause: Select<D, U>, _ queryClauses: [QueryClause]) throws -> U? where D : DynamicObject, U : QueryableAttributeTypeParameters
froma
Fromclause indicating the entity typeselectClausea
Select<U>clause indicating the properties to fetch, and with the generic type indicating the return type.queryClausesa series of
QueryClauseinstances for the query request. AcceptsWhere,OrderBy,GroupBy, andTweakclauses.Return Value
the result of the the query, or
nilif no match was found. The type of the return value is specified by the generic type of theSelect<U>parameter. -
Queries a property value or aggregate as specified by the
QueryChainableBuilderTypebuilt from a chain of clauses.A
query
differs from afetch
in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.let averageAdultAge = CoreStore.queryValue( From<MyPersonEntity>() .select(Int.self, .average(\.age)) .where(\.age > 18) )Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func queryValue<B>(_ clauseChain: B) throws -> B.ResultType? where B : QueryChainableBuilderType, B.ResultType : QueryableAttributeTypeParameters
clauseChaina
QueryChainableBuilderTypeindicating the property/aggregate to fetch and the series of queries for the request.Return Value
the result of the the query as specified by the
QueryChainableBuilderType, ornilif no match was found. -
Using the
defaultStack, queries a dictionary of attribute values as specified by theQueryClauses. Requires at least aSelectclause, and optionalWhere,OrderBy,GroupBy, andTweakclauses.A
query
differs from afetch
in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func queryAttributes<D>(_ from: From<D>, _ selectClause: Select<D, NSDictionary>, _ queryClauses: QueryClause...) throws -> [[String : Any]] where D : DynamicObjectParameters
froma
Fromclause indicating the entity typeselectClausea
Select<U>clause indicating the properties to fetch, and with the generic type indicating the return type.queryClausesa series of
QueryClauseinstances for the query request. AcceptsWhere,OrderBy,GroupBy, andTweakclauses.Return Value
the result of the the query. The type of the return value is specified by the generic type of the
Select<U>parameter. -
Using the
defaultStack, queries a dictionary of attribute values as specified by theQueryClauses. Requires at least aSelectclause, and optionalWhere,OrderBy,GroupBy, andTweakclauses.A
query
differs from afetch
in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func queryAttributes<D>(_ from: From<D>, _ selectClause: Select<D, NSDictionary>, _ queryClauses: [QueryClause]) throws -> [[String : Any]] where D : DynamicObjectParameters
froma
Fromclause indicating the entity typeselectClausea
Select<U>clause indicating the properties to fetch, and with the generic type indicating the return type.queryClausesa series of
QueryClauseinstances for the query request. AcceptsWhere,OrderBy,GroupBy, andTweakclauses.Return Value
the result of the the query. The type of the return value is specified by the generic type of the
Select<U>parameter. -
Queries a dictionary of attribute values or as specified by the
QueryChainableBuilderTypebuilt from a chain of clauses.A
query
differs from afetch
in that it only retrieves values already stored in the persistent store. As such, values from unsaved transactions or contexts will not be incorporated in the query result.let results = CoreStore.queryAttributes( From<MyPersonEntity>() .select( NSDictionary.self, .attribute(\.age, as: "age"), .count(\.age, as: "numberOfPeople") ) .groupBy(\.age) ) for dictionary in results! { let age = dictionary["age"] as! Int let count = dictionary["numberOfPeople"] as! Int print("There are \(count) people who are \(age) years old." }Throws
CoreStoreError.persistentStoreNotFoundif the specified entity could not be found in any store’s schema.Declaration
Swift
public static func queryAttributes<B>(_ clauseChain: B) throws -> [[String : Any]] where B : QueryChainableBuilderType, B.ResultType == NSDictionaryParameters
clauseChaina
QueryChainableBuilderTypeindicating the properties to fetch and the series of queries for the request.Return Value
the result of the the query as specified by the
QueryChainableBuilderType
-
Returns the
defaultStack‘s model version. The version string is the same as the name of a version-specific .xcdatamodeld file orCoreStoreSchema.Declaration
Swift
public static var modelVersion: String { get } -
Returns the entity name-to-class type mapping from the
defaultStack‘s model.Declaration
Swift
public static func entityTypesByName(for type: NSManagedObject.Type) -> [EntityName : NSManagedObject.Type] -
Returns the entity name-to-class type mapping from the
defaultStack‘s model.Declaration
Swift
public static func entityTypesByName(for type: CoreStoreObject.Type) -> [EntityName : CoreStoreObject.Type] -
Returns the
NSEntityDescriptionfor the specifiedNSManagedObjectsubclass fromdefaultStack‘s model.Declaration
Swift
public static func entityDescription(for type: NSManagedObject.Type) -> NSEntityDescription? -
Returns the
NSEntityDescriptionfor the specifiedCoreStoreObjectsubclass fromdefaultStack‘s model.Declaration
Swift
public static func entityDescription(for type: CoreStoreObject.Type) -> NSEntityDescription? -
Creates an
SQLiteStorewith default parameters and adds it to thedefaultStack. This method blocks until completion.try CoreStore.addStorageAndWait()Declaration
Swift
@discardableResult public static func addStorageAndWait() throws -> SQLiteStoreReturn Value
the local SQLite storage added to the
defaultStack -
Adds a
StorageInterfaceto thedefaultStackand blocks until completion.try CoreStore.addStorageAndWait(InMemoryStore(configuration: "Config1"))Throws
aCoreStoreErrorvalue indicating the failureDeclaration
Swift
@discardableResult public static func addStorageAndWait<T>(_ storage: T) throws -> T where T : StorageInterfaceParameters
storagethe
StorageInterfaceReturn Value
the
StorageInterfaceadded to thedefaultStack -
Adds a
LocalStorageto thedefaultStackand blocks until completion.try CoreStore.addStorageAndWait(SQLiteStore(configuration: "Config1"))Throws
aCoreStoreErrorvalue indicating the failureDeclaration
Swift
@discardableResult public static func addStorageAndWait<T>(_ storage: T) throws -> T where T : LocalStorageParameters
storagethe local storage
Return Value
the local storage added to the
defaultStack. Note that this may not always be the same instance as the parameter argument if a previousLocalStoragewas already added at the same URL and with the same configuration. -
Adds a
CloudStorageto thedefaultStackand blocks until completion.guard let storage = ICloudStore( ubiquitousContentName: "MyAppCloudData", ubiquitousContentTransactionLogsSubdirectory: "logs/config1", ubiquitousContainerID: "iCloud.com.mycompany.myapp.containername", ubiquitousPeerToken: "9614d658014f4151a95d8048fb717cf0", configuration: "Config1", cloudStorageOptions: .recreateLocalStoreOnModelMismatch ) else { // iCloud is not available on the device return } try CoreStore.addStorageAndWait(storage)Throws
aCoreStoreErrorvalue indicating the failureDeclaration
Swift
@discardableResult public static func addStorageAndWait<T>(_ storage: T) throws -> T where T : CloudStorageParameters
storagethe local storage
Return Value
the cloud storage added to the stack. Note that this may not always be the same instance as the parameter argument if a previous
CloudStoragewas already added at the same URL and with the same configuration.
-
Using the
defaultStack, performs a transaction asynchronously whereNSManagedObjectorCoreStoreObjectcreates, updates, and deletes can be made. The changes are commited automatically after thetaskclosure returns. On success, the value returned from closure will be the wrapped as.success(T)in thecompletion‘sResult<T>. Any errors thrown from inside thetaskwill be reported as.failure(CoreStoreError). To cancel/rollback changes, calltry transaction.cancel(), which throws aCoreStoreError.userCancelled.Declaration
Swift
public static func perform<T>(asynchronous task: @escaping (_ transaction: AsynchronousDataTransaction) throws -> T, completion: @escaping (AsynchronousDataTransaction.Result<T>) -> Void)Parameters
taskthe asynchronous closure where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent
NSManagedObjectContext.completionthe closure executed after the save completes. The
Resultargument of the closure will either wrap the return value oftask, or any uncaught errors thrown from withintask. Cancelledtasks will be indicated by.failure(error: CoreStoreError.userCancelled). Custom errors thrown by the user will be wrapped inCoreStoreError.userError(error: Error). -
Using the
defaultStack, performs a transaction asynchronously whereNSManagedObjectorCoreStoreObjectcreates, updates, and deletes can be made. The changes are commited automatically after thetaskclosure returns. On success, the value returned from closure will be the argument of thesuccessclosure. Any errors thrown from inside thetaskwill be wrapped in aCoreStoreErrorand reported in thefailureclosure. To cancel/rollback changes, calltry transaction.cancel(), which throws aCoreStoreError.userCancelled.Declaration
Swift
public static func perform<T>(asynchronous task: @escaping (_ transaction: AsynchronousDataTransaction) throws -> T, success: @escaping (T) -> Void, failure: @escaping (CoreStoreError) -> Void)Parameters
taskthe asynchronous closure where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent
NSManagedObjectContext.successthe closure executed after the save succeeds. The
Targument of the closure will be the value returned fromtask.failurethe closure executed if the save fails or if any errors are thrown within
task. Cancelledtasks will be indicated byCoreStoreError.userCancelled. Custom errors thrown by the user will be wrapped inCoreStoreError.userError(error: Error). -
Using the
defaultStack, performs a transaction synchronously whereNSManagedObjectorCoreStoreObjectcreates, updates, and deletes can be made. The changes are commited automatically after thetaskclosure returns. On success, the value returned from closure will be the return value ofperform(synchronous:). Any errors thrown from inside thetaskwill be thrown fromperform(synchronous:). To cancel/rollback changes, calltry transaction.cancel(), which throws aCoreStoreError.userCancelled.Throws
aCoreStoreErrorvalue indicating the failure. Cancelledtasks will be indicated byCoreStoreError.userCancelled. Custom errors thrown by the user will be wrapped inCoreStoreError.userError(error: Error).Declaration
Swift
public static func perform<T>(synchronous task: ((_ transaction: SynchronousDataTransaction) throws -> T), waitForAllObservers: Bool = true) throws -> TParameters
taskthe synchronous non-escaping closure where creates, updates, and deletes can be made to the transaction. Transaction blocks are executed serially in a background queue, and all changes are made from a concurrent
NSManagedObjectContext.waitForAllObserversWhen
true, this method waits for all observers to be notified of the changes before returning. This results in more predictable data update order, but may risk triggering deadlocks. Whenfalse, this method does not wait for observers to be notified of the changes before returning. This results in lower risk for deadlocks, but the updated data may not have been propagated to theDataStackafter returning. Defaults totrue.Return Value
the value returned from
task -
Using the
defaultStack, begins a non-contiguous transaction whereNSManagedObjectorCoreStoreObjectcreates, updates, and deletes can be made. This is useful for making temporary changes, such as partially filled forms.- prameter supportsUndo:
undo(),redo(), androllback()methods are only available when this parameter istrue, otherwise those method will raise an exception. Defaults tofalse. Note that turning on Undo support may heavily impact performance especially on iOS or watchOS where memory is limited.
Declaration
Swift
public static func beginUnsafe(supportsUndo: Bool = false) -> UnsafeDataTransactionReturn Value
a
UnsafeDataTransactioninstance where creates, updates, and deletes can be made. - prameter supportsUndo:
-
Refreshes all registered objects
NSManagedObjects orCoreStoreObjects in thedefaultStack.Declaration
Swift
public static func refreshAndMergeAllObjects()
View on GitHub
CoreStore Enumeration Reference