added way to store userInfo in DataStack and in transactions

This commit is contained in:
John Estropia
2017-04-18 11:29:16 +09:00
parent a73306fecb
commit b1972b82f1
2 changed files with 82 additions and 0 deletions

View File

@@ -442,6 +442,43 @@ public final class DataStack: Equatable {
}
// MARK: 3rd Party Utilities
/**
Allow external libraries to store custom data in the `DataStack`. App code should rarely have a need for this.
```
enum Static {
static var myDataKey: Void?
}
CoreStore.defaultStack[userInfoKey: &Static.myDataKey] = myObject
```
- Important: Do not use this method to store thread-sensitive data.
- parameter userInfoKey: the key for custom data. Make sure this is a static pointer that will never be changed.
- returns: A custom data identified by `userInfoKey`
*/
public subscript(userInfoKey key: UnsafeRawPointer) -> Any? {
get {
self.userInfoLock.lock()
defer {
self.userInfoLock.unlock()
}
return self.userInfo[key]
}
set {
self.userInfoLock.lock()
defer {
self.userInfoLock.unlock()
}
self.userInfo[key] = newValue
}
}
// MARK: Equatable
public static func == (lhs: DataStack, rhs: DataStack) -> Bool {
@@ -571,6 +608,8 @@ public final class DataStack: Equatable {
private var persistentStoresByFinalConfiguration = [String: NSPersistentStore]()
private var finalConfigurationsByEntityIdentifier = [EntityIdentifier: Set<String>]()
private var userInfo: [UnsafeRawPointer: Any] = [:]
private let userInfoLock = NSRecursiveLock()
deinit {

View File

@@ -438,6 +438,43 @@ public /*abstract*/ class BaseDataTransaction {
}
// MARK: 3rd Party Utilities
/**
Allow external libraries to store custom data in the transaction. App code should rarely have a need for this.
```
enum Static {
static var myDataKey: Void?
}
transaction[userInfoKey: &Static.myDataKey] = myObject
```
- Important: Do not use this method to store thread-sensitive data.
- parameter userInfoKey: the key for custom data. Make sure this is a static pointer that will never be changed.
- returns: A custom data identified by `userInfoKey`
*/
public subscript(userInfoKey key: UnsafeRawPointer) -> Any? {
get {
self.userInfoLock.lock()
defer {
self.userInfoLock.unlock()
}
return self.userInfo[key]
}
set {
self.userInfoLock.lock()
defer {
self.userInfoLock.unlock()
}
self.userInfo[key] = newValue
}
}
// MARK: Internal
internal let context: NSManagedObjectContext
@@ -476,4 +513,10 @@ public /*abstract*/ class BaseDataTransaction {
return self.bypassesQueueing || self.transactionQueue.cs_isCurrentExecutionContext()
}
// MARK: Private
private var userInfo: [UnsafeRawPointer: Any] = [:]
private let userInfoLock = NSRecursiveLock()
}