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:
- Initialize a ThreadSafeReference with the thread-confined object.
- Pass that ThreadSafeReference to a destination thread or queue.
- 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调研--草稿的更多相关文章
- Realm Swift
Realm Swift 当前这个翻译,主要是方便我自己查阅api,有非常多地方写的比較晦涩或者没有翻译,敬请谅解 version 0.98.7 官方文档 參考文献 Realm支持类型 String,N ...
- iOS中 Realm的学习与使用 韩俊强的博客
每日更新关注:http://weibo.com/hanjunqiang 新浪微博! 有问题或技术交流可以咨询!欢迎加入! 这篇直接搬了一份官方文档过来看的 由于之前没用markdown搞的乱七八糟的 ...
- fir.im Weekly - 如何打造真正的工程师文化
好的工程师,无法忍受低效且无趣的工作.优秀的技术团队应该自上而下的地推进技术平台化建设.DevOps.自动化构建.测试和部署流程,积极采用合适的第三方工具或创造工具,进行周期性的前沿技术分享等等. 先 ...
- 开发辅助 | 前端开发工程师对 UI设计、交互设计的认知
1.UI 用户界面 UI:User Interfase 用户界面 UID:User Interfase Designer 用户界面设计师,多指移动 app 的界面设计: 2.一个合格的 UI 设计师, ...
- Swift Realm 完整使用记录
新项目用到了数据库,本来之前用的都是 SQL,但是语法写的实在是恶心,所以使用 Realm 尝试一下. 1.我使用的 pod 库,所以先 pod 库安装一下,安装完别忘了先编译一下,不然 import ...
- 使用 Realm 和 Swift 创建 ToDo 应用
原文出处: HOSSAM GHAREEB 译文出处:Prayer’s blog(@EclipsePrayer) 智能手机的快速发展的同时,涌现出了很多对开发者友好的开发工具,这些工具不仅使得开发变 ...
- Swift之代码混淆的调研实施小记
背景: 最近做APP备案,需要对项目做一系列对优化改进,其中就包括了代码混淆,顾名思义,混淆是为了代码安全,是为了增加逆向破解的难度与复杂度. 目前市面上,免费和付费都有,一些公司对APP加固已经做成 ...
- 为什么说swift是面向协议编程--草稿
为什么说swift是面向协议编程 public protocol ReactiveCompatible { /// Extended type associatedtype CompatibleTyp ...
- OpenStack调研:OpenStack是什么、版本演变、组件关系(Havana)、同类产品及个人感想
一点调研资料,比较浅,只是觉得部分内容比较有用,记在这里: 首先,关于云计算,要理解什么是SAAS.PAAS.IAAS,这里不述:关于虚拟化,需要知道什么是Hypervisor,这里也不述: Open ...
随机推荐
- WebApi系列~不支持put和delete请求的解决方法
回到目录 原因 由于安装了webDAV模块引起的,在web.config里的system.webserver节点,将webdav模块移动 将http请求的权限开放 实现 <system.webS ...
- Asp.net Core 使用Jenkins + Dockor 实现持续集成、自动化部署(二):部署
前面又是废话 我之前写过: Asp.Net Core 程序部署到Linux(centos)生产环境(一):普通部署 Asp.Net Core 程序部署到Linux(centos)生产环境(二):doc ...
- 使用ajax+php+mysql实现数据库定时刷新
php版本5.5.9,mysql版本5.7. 所以php链接mysql就是使用mysql_connect. 如果遇到了连接时没有成功也没有失败的情况时,就重启mysql,或重启docker(睡一觉就好 ...
- js内存深入学习(二)
继上一篇文章 js内存深入学习(一) 3. 内存泄漏 对于持续运行的服务进程(daemon),必须及时释放不再用到的内存.否则,内存占用越来越高,轻则影响系统性能,重则导致进程崩溃. 对于不再用到的内 ...
- VS2017移动开发(C#、VB.NET)——Numeric控件的使用方式
Visual Studio 2017移动开发 控件介绍和使用方式:Numeric控件 Smobiler开发平台,.NET移动开发 一. 样式一 我们要实现上图中的效果,需要如下的操作 ...
- Java开发笔记(五十)几种开放性修饰符
前面介绍子类继承父类的时候,提到了public(公共)和private(私有)两个修饰符,其中public表示它所修饰的实体是允许外部访问的:而private表示它所修饰的实体不允许外部访问,只能在当 ...
- mysql修改连接数
方法一: 进入MySQL安装目录 打开MySQL配置文件 my.ini 或 my.cnf查找 max_connections=100 修改为 max_connections=1000 服务里重起M ...
- SpringBoot项目部署到服务器上,tomcat不启动该项目
今天lz把项目重新传到服务器上后,重启tomcat遇到个问题,就是这个tomcat怎么都不启动这个项目,别的项目都没事,一番查找后发现问题所在. 我们先建个SpringBoot工程,重现一下问题: 写 ...
- 实现PHP内部的通知机制,如当一个类的属性发生变化时,另外一个类就可以收到通知
设计模式:观察者模式 当一个对象的状态发生改变时,依赖他的对象会全部收到通知,并自动更新. 使用场景 一个事件发生后,要执行一连串更新操作.传统的编程方式,就是在事件的代码之后直接加入处理逻辑,当更新 ...
- Django---forms表单使用(1)
使用过Django的同学应该都比较清楚,Django的表单功能是十分强大的,可以完成数据的校验等功能. 下面讲下常用的表单类型.我们讲下创建表单到前台可以正常显示的步骤: 一.创建表单类(可以直接在v ...