Added a "userInfo" property to relevant types to allow external code to store custom data

This commit is contained in:
John Estropia
2017-04-20 16:40:27 +09:00
parent fd14a18248
commit a543a4c94a
6 changed files with 160 additions and 114 deletions

View File

@@ -444,64 +444,13 @@ public /*abstract*/ class BaseDataTransaction {
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?
static var myDataKey: Void?
}
transaction[userInfoKey: &Static.myDataKey] = myObject
transaction.userInfo[&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
}
}
/**
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?
}
CoreStore.defaultStack[userInfoKey: &Static.myDataKey, lazyInit: { MyObject() }] = 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.
- parameter lazyInit: a closure to use to lazily-initialize the data
- returns: A custom data identified by `userInfoKey`
*/
public subscript(userInfoKey key: UnsafeRawPointer, lazyInit closure: () -> Any) -> Any {
self.userInfoLock.lock()
defer {
self.userInfoLock.unlock()
}
if let value = self.userInfo[key] {
return value
}
let value = closure()
self.userInfo[key] = value
return value
}
private let userInfo = UserInfo()
// MARK: Internal
@@ -542,10 +491,4 @@ public /*abstract*/ class BaseDataTransaction {
return self.bypassesQueueing || self.transactionQueue.cs_isCurrentExecutionContext()
}
// MARK: Private
private var userInfo: [UnsafeRawPointer: Any] = [:]
private let userInfoLock = NSRecursiveLock()
}