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

什么意思?

realm swift调研--草稿的更多相关文章

  1. Realm Swift

    Realm Swift 当前这个翻译,主要是方便我自己查阅api,有非常多地方写的比較晦涩或者没有翻译,敬请谅解 version 0.98.7 官方文档 參考文献 Realm支持类型 String,N ...

  2. iOS中 Realm的学习与使用 韩俊强的博客

    每日更新关注:http://weibo.com/hanjunqiang  新浪微博! 有问题或技术交流可以咨询!欢迎加入! 这篇直接搬了一份官方文档过来看的 由于之前没用markdown搞的乱七八糟的 ...

  3. fir.im Weekly - 如何打造真正的工程师文化

    好的工程师,无法忍受低效且无趣的工作.优秀的技术团队应该自上而下的地推进技术平台化建设.DevOps.自动化构建.测试和部署流程,积极采用合适的第三方工具或创造工具,进行周期性的前沿技术分享等等. 先 ...

  4. 开发辅助 | 前端开发工程师对 UI设计、交互设计的认知

    1.UI 用户界面 UI:User Interfase 用户界面 UID:User Interfase Designer 用户界面设计师,多指移动 app 的界面设计: 2.一个合格的 UI 设计师, ...

  5. Swift Realm 完整使用记录

    新项目用到了数据库,本来之前用的都是 SQL,但是语法写的实在是恶心,所以使用 Realm 尝试一下. 1.我使用的 pod 库,所以先 pod 库安装一下,安装完别忘了先编译一下,不然 import ...

  6. 使用 Realm 和 Swift 创建 ToDo 应用

    原文出处: HOSSAM GHAREEB   译文出处:Prayer’s blog(@EclipsePrayer) 智能手机的快速发展的同时,涌现出了很多对开发者友好的开发工具,这些工具不仅使得开发变 ...

  7. Swift之代码混淆的调研实施小记

    背景: 最近做APP备案,需要对项目做一系列对优化改进,其中就包括了代码混淆,顾名思义,混淆是为了代码安全,是为了增加逆向破解的难度与复杂度. 目前市面上,免费和付费都有,一些公司对APP加固已经做成 ...

  8. 为什么说swift是面向协议编程--草稿

    为什么说swift是面向协议编程 public protocol ReactiveCompatible { /// Extended type associatedtype CompatibleTyp ...

  9. OpenStack调研:OpenStack是什么、版本演变、组件关系(Havana)、同类产品及个人感想

    一点调研资料,比较浅,只是觉得部分内容比较有用,记在这里: 首先,关于云计算,要理解什么是SAAS.PAAS.IAAS,这里不述:关于虚拟化,需要知道什么是Hypervisor,这里也不述: Open ...

随机推荐

  1. 基础才是重中之重~delegate里的Invoke和BeginInvoke

    回到目录 Invoke和BeginInvoke都是调用委托实体的方法,前者是同步调用,即它运行在主线程上,当Invode处理时间长时,会出现阻塞的情况,而BeginInvod是异步操作,它会从新开启一 ...

  2. RDIFramework.NET ━ .NET快速信息化系统开发框架 V3.2->Web版本“产品管理”事例编辑界面新增KindEditor复文本编辑控件

    KindEditor是一套开源的HTML可视化编辑器,主要用于让用户在网站上获得所见即所得编辑效果,兼容IE.Firefox.Chrome.Safari.Opera等主流浏览器.KindEditor使 ...

  3. jumpserver篇--安装(高可用性 mariadb+haproxy)

    1. 需求 为了解决目前登陆方式多种多样,防火墙配置复杂,历史操作无记录,用户权限混乱等等 2. Jumpserver测试环境搭建 2.1. 环境 os:CentOS release 6.8 mini ...

  4. [一]class 文件浅析 .class文件格式详解 字段方法属性常量池字段 class文件属性表 数据类型 数据结构

    前言概述  本文旨在讲解class文件的整体结构信息,阅读本文后应该可以完整的了解class文件的格式以及各个部分的逻辑组成含义   class文件包含了java虚拟机指令集 和  符号表   以及若 ...

  5. springboot情操陶冶-初识springboot

    前言:springboot由于其轻便和去配置化等的特性已经被广泛应用,基于时代潮流以及不被鄙视,笔者于是开辟此篇开始认识springboot 前话 springboot是基于spring而开发的轻量级 ...

  6. 【憩园】C#并发编程之概述

    写在前面 并发编程一直都存在,只不过过去的很长时间里,比较难以实现,随着互联网的发展,人口红利的释放,更加友好的支持并发编程已经成了主流编程语言的标配,而对于软件开发人员来说,没有玩过并发编程都会有点 ...

  7. Redis的复制是如何实现的?

    前言 关系数据库通常会使用一个主服务器向多个从服务器发送更新,并使用从服务器来处理所有的读请求,Redis采用了同样方法来实现自己的复制特性. 简单总结起来就是:在接收到主服务器发送的数据初始副本之后 ...

  8. 【Zabbix】zabbix设置邮件报警

    目录 Zabbix设置邮件报警 1.安装sendmail或postfix 2.安装邮件发送工具mailx . 3.配置mail 4. 测试邮件发送 5.编写邮件发送脚本sendmail.sh 6.设置 ...

  9. webpack4.0各个击破(2)—— CSS篇

    webpack作为前端最火的构建工具,是前端自动化工具链最重要的部分,使用门槛较高.本系列是笔者自己的学习记录,比较基础,希望通过问题 + 解决方式的模式,以前端构建中遇到的具体需求为出发点,学习we ...

  10. InterLocked学习笔记

    在进行多线程编程的时候特别重要的一点就是多线程的同步,什么是同步呢?字面意思就是使多个不在同一线程执行的代码统一到一个线程中执行,但是对执行中的线程过程却无法控制,这就造成了多个线程可能同时操作同一个 ...