realm swift调研--草稿

realm swift调研:

 

After you have added the object to the Realm you can continue using it, and all changes you make to it will be persisted (and must be made within a write transaction). Any changes are made available to other threads that use the same Realm when the write transaction is committed.

Please note that writes block each other, and will block the thread they are made on if multiple writes are in progress. This is similar to other persistence solutions and we recommend that you use the usual best practice for this situation: offloading your writes to a separate thread.

Thanks to Realm’s MVCC architecture, reads are not blocked while a write transaction is open. Unless you need to make simultaneous writes from many threads at once, you should favor larger write transactions that do more work over many fine-grained write transactions. When you commit a write transaction to a Realm, all other instances of that Realm will be notified, and be updated automatically.

 

 

Using a Realm across threads

To access the same Realm file from different threads, you must initialize a new Realm to get a different instance for every thread of your app. As long as you specify the same configuration, all Realm instances will map to the same file on disk.

 

 

Realm exposes a mechanism to safely pass thread-confined instances in three steps:

  1. Initialize a ThreadSafeReference with the thread-confined object.
  2. Pass that ThreadSafeReference to a destination thread or queue.
  3. Resolve this reference on the target Realm by calling Realm.resolve(_:). Use the returned object as you normally would.

 

 

let person = Person(name: "Jane")

try! realm.write {

    realm.add(person)

}

let personRef = ThreadSafeReference(to: person)

DispatchQueue(label: "background").async {

    autoreleasepool {

        let realm = try! Realm()

        guard let person = realm.resolve(personRef) else {

            return // person was deleted

        }

        try! realm.write {

            person.name = "Jane Doe"

        }

    }

}

A ThreadSafeReference object must be resolved at most once. Failing to resolve a ThreadSafeReference will result in the source version of the Realm being pinned until the reference is deallocated. For this reason, ThreadSafeReference should be short-lived.

 

The block will be called with ObjectChange.error containing an NSError if an error occurs. The block will never be called again.

 

class StepCounter: Object {

    @objc dynamic var steps = 0

}

 

let stepCounter = StepCounter()

let realm = try! Realm()

try! realm.write {

    realm.add(stepCounter)

}

var token : NotificationToken?

token = stepCounter.observe { change in

    switch change {

    case .change(let properties):

        for property in properties {

            if property.name == "steps" && property.newValue as! Int > 1000 {

                print("Congratulations, you've exceeded 1000 steps.")

                token = nil

            }

        }

    case .error(let error):

        print("An error occurred: \(error)")

    case .deleted:

        print("The object was deleted.")

    }

}

 

+

Auto-updating results

Results instances are live, auto-updating views into the underlying data, which means results never have to be re-fetched. They always reflect the current state of the Realm on the current thread, including during write transactions on the current thread. The one exception to this is when using for...in enumeration, which will always enumerate over the objects which matched the query when the enumeration is begun, even if some of them are deleted or modified to be excluded by the filter during the enumeration.

 

let puppies = realm.objects(Dog.self).filter("age < 2")

puppies.count // => 0

try! realm.write {

    realm.create(Dog.self, value: ["name": "Fido", "age": 1])

}

puppies.count // => 1

 

?代理模式

 

This applies to all Results: all objects, filtered and chained.

This property of Results not only keeps Realm fast and efficient, it allows your code to be simpler and more reactive. For example, if your view controller relies on the results of a query, you can store the Results in a property and access it without having to make sure to refresh its data prior to each access.

 

 

Realm makes concurrent usage easy by ensuring that each thread always has a consistent view of the Realm. You can have any number of threads working on the same Realms in parallel, and since they all have their own snapshots, they will never cause each other to see inconsistent state.

The only thing you have to be aware of is that you cannot have multiple threads sharing the same instances of Realm objects. If multiple threads need to access the same objects they will each need to get their own instances (otherwise changes happening on one thread could cause other threads to see incomplete or inconsistent data).

Seeing changes from other threads

On the main UI thread (or any thread with a runloop) objects will automatically update with changes from other threads between each iteration of the runloop. At any other time you will be working on the snapshot, so individual methods always see a consistent view and never have to worry about what happens on other threads.

When you initially open a Realm on a thread, its state will be based off the most recent successful write commit, and it will remain on that version until refreshed. Realms are automatically refreshed at the start of every runloop iteration, unless Realm’s autorefresh property is set to NO. If a thread has no runloop (which is generally the case in a background thread), then Realm.refresh() must be called manually in order to advance the transaction to the most recent state.

Realms are also refreshed when write transactions are committed (Realm.commitWrite()).

 

 

Threads

Although Realm files can be accessed by multiple threads concurrently, you cannot directly pass Realms, Realm objects, queries, and results between threads. If you need to pass Realm objects between threads, you can use the ThreadSafeReference API. Read more about Realm’s threading.

 

https://realm.io/docs/swift/latest/#threading

 

https://realm.io/docs/swift/latest/#model-inheritance

 

 

什么意思?

上一篇:tensorflow中协调器 tf.train.Coordinator 和入队线程启动器 tf.train.start_queue_runners


下一篇:NIO在Windows下占用大量CPU资源原因详解