beste Ansatz, um die Methode als Erweiterung für Realm
Objekt zu schreiben wäre.
Für Swift 3+
extension Realm {
/// Performs actions contained within the given block
/// inside a write transaction with completion block.
///
/// - parameter block: write transaction block
/// - parameter completion: completion executed after transaction block
func write(transaction block: (Void) -> Void, completion: (Void) -> Void) throws {
try write(block)
completion()
}
}
Swift 2,0
extension Realm {
/** Performs actions contained within the given block inside a write transaction with
completion block.
- parameter block: write transaction block
- completion: completion executed after transaction block
*/
func write(@noescape transactionBlock block: Void ->(), completion: Void ->()) throws {
do {
try write(block)
completion()
} catch {
throw error
}
}
}
Jetzt können Sie die Erweiterung verwenden wie eine normale write(_:)
Methode.
let realm = try! Realm()
let object = SomeObject()
try! realm.write(
transactionBlock: {
realm.add(object)
},
completion: {
print("Write transaction finished")
})
Dies ist die richtige Antwort – Donamite