added a way to lazily-initialize user info data

This commit is contained in:
John Estropia
2017-04-18 12:02:39 +09:00
parent b1972b82f1
commit 94e6db669f
2 changed files with 58 additions and 1 deletions

View File

@@ -454,7 +454,6 @@ public final class DataStack: Equatable {
```
- 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? {
@@ -478,6 +477,35 @@ public final class DataStack: Equatable {
}
}
/**
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, 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
}
// MARK: Equatable

View File

@@ -474,6 +474,35 @@ 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?
}
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
}
// MARK: Internal