Realm.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2014 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. import Foundation
  19. import Realm
  20. import Realm.Private
  21. /**
  22. A `Realm` instance (also referred to as "a Realm") represents a Realm database.
  23. Realms can either be stored on disk (see `init(path:)`) or in memory (see `Configuration`).
  24. `Realm` instances are cached internally, and constructing equivalent `Realm` objects (for example, by using the same
  25. path or identifier) produces limited overhead.
  26. If you specifically want to ensure a `Realm` instance is destroyed (for example, if you wish to open a Realm, check
  27. some property, and then possibly delete the Realm file and re-open it), place the code which uses the Realm within an
  28. `autoreleasepool {}` and ensure you have no other strong references to it.
  29. - warning: `Realm` instances are not thread safe and cannot be shared across threads or dispatch queues. You must
  30. construct a new instance for each thread in which a Realm will be accessed. For dispatch queues, this means
  31. that you must construct a new instance in each block which is dispatched, as a queue is not guaranteed to
  32. run all of its blocks on the same thread.
  33. */
  34. public final class Realm {
  35. // MARK: Properties
  36. /// The `Schema` used by the Realm.
  37. public var schema: Schema { return Schema(rlmRealm.schema) }
  38. /// The `Configuration` value that was used to create the `Realm` instance.
  39. public var configuration: Configuration { return Configuration.fromRLMRealmConfiguration(rlmRealm.configuration) }
  40. /// Indicates if the Realm contains any objects.
  41. public var isEmpty: Bool { return rlmRealm.isEmpty }
  42. // MARK: Initializers
  43. /**
  44. Obtains an instance of the default Realm.
  45. The default Realm is persisted as *default.realm* under the *Documents* directory of your Application on iOS, and
  46. in your application's *Application Support* directory on OS X.
  47. The default Realm is created using the default `Configuration`, which can be changed by setting the
  48. `Realm.Configuration.defaultConfiguration` property to a new value.
  49. - throws: An `NSError` if the Realm could not be initialized.
  50. */
  51. public convenience init() throws {
  52. let rlmRealm = try RLMRealm(configuration: RLMRealmConfiguration.default())
  53. self.init(rlmRealm)
  54. }
  55. /**
  56. Obtains a `Realm` instance with the given configuration.
  57. - parameter configuration: A configuration value to use when creating the Realm.
  58. - throws: An `NSError` if the Realm could not be initialized.
  59. */
  60. public convenience init(configuration: Configuration) throws {
  61. let rlmRealm = try RLMRealm(configuration: configuration.rlmConfiguration)
  62. self.init(rlmRealm)
  63. }
  64. /**
  65. Obtains a `Realm` instance persisted at a specified file URL.
  66. - parameter fileURL: The local URL of the file the Realm should be saved at.
  67. - throws: An `NSError` if the Realm could not be initialized.
  68. */
  69. public convenience init(fileURL: URL) throws {
  70. var configuration = Configuration.defaultConfiguration
  71. configuration.fileURL = fileURL
  72. try self.init(configuration: configuration)
  73. }
  74. // MARK: Async
  75. /**
  76. Asynchronously open a Realm and deliver it to a block on the given queue.
  77. Opening a Realm asynchronously will perform all work needed to get the Realm to
  78. a usable state (such as running potentially time-consuming migrations) on a
  79. background thread before dispatching to the given queue. In addition,
  80. synchronized Realms wait for all remote content available at the time the
  81. operation began to be downloaded and available locally.
  82. - parameter configuration: A configuration object to use when opening the Realm.
  83. - parameter callbackQueue: The dispatch queue on which the callback should be run.
  84. - parameter callback: A callback block. If the Realm was successfully opened, an
  85. it will be passed in as an argument.
  86. Otherwise, a `Swift.Error` describing what went wrong will be
  87. passed to the block instead.
  88. - note: The returned Realm is confined to the thread on which it was created.
  89. Because GCD does not guarantee that queues will always use the same
  90. thread, accessing the returned Realm outside the callback block (even if
  91. accessed from `callbackQueue`) is unsafe.
  92. */
  93. public static func asyncOpen(configuration: Realm.Configuration = .defaultConfiguration,
  94. callbackQueue: DispatchQueue = .main,
  95. callback: @escaping (Realm?, Swift.Error?) -> Void) {
  96. RLMRealm.asyncOpen(with: configuration.rlmConfiguration, callbackQueue: callbackQueue) { rlmRealm, error in
  97. callback(rlmRealm.flatMap(Realm.init), error)
  98. }
  99. }
  100. // MARK: Transactions
  101. /**
  102. Performs actions contained within the given block inside a write transaction.
  103. If the block throws an error, the transaction will be canceled and any
  104. changes made before the error will be rolled back.
  105. Only one write transaction can be open at a time for each Realm file. Write
  106. transactions cannot be nested, and trying to begin a write transaction on a
  107. Realm which is already in a write transaction will throw an exception.
  108. Calls to `write` from `Realm` instances for the same Realm file in other
  109. threads or other processes will block until the current write transaction
  110. completes or is cancelled.
  111. Before beginning the write transaction, `write` updates the `Realm`
  112. instance to the latest Realm version, as if `refresh()` had been called,
  113. and generates notifications if applicable. This has no effect if the Realm
  114. was already up to date.
  115. - parameter block: The block containing actions to perform.
  116. - throws: An `NSError` if the transaction could not be completed successfully.
  117. If `block` throws, the function throws the propagated `ErrorType` instead.
  118. */
  119. public func write(_ block: (() throws -> Void)) throws {
  120. beginWrite()
  121. do {
  122. try block()
  123. } catch let error {
  124. if isInWriteTransaction { cancelWrite() }
  125. throw error
  126. }
  127. if isInWriteTransaction { try commitWrite() }
  128. }
  129. /**
  130. Begins a write transaction on the Realm.
  131. Only one write transaction can be open at a time for each Realm file. Write
  132. transactions cannot be nested, and trying to begin a write transaction on a
  133. Realm which is already in a write transaction will throw an exception.
  134. Calls to `beginWrite` from `Realm` instances for the same Realm file in
  135. other threads or other processes will block until the current write
  136. transaction completes or is cancelled.
  137. Before beginning the write transaction, `beginWrite` updates the `Realm`
  138. instance to the latest Realm version, as if `refresh()` had been called,
  139. and generates notifications if applicable. This has no effect if the Realm
  140. was already up to date.
  141. It is rarely a good idea to have write transactions span multiple cycles of
  142. the run loop, but if you do wish to do so you will need to ensure that the
  143. Realm participating in the write transaction is kept alive until the write
  144. transaction is committed.
  145. */
  146. public func beginWrite() {
  147. rlmRealm.beginWriteTransaction()
  148. }
  149. /**
  150. Commits all write operations in the current write transaction, and ends
  151. the transaction.
  152. After saving the changes and completing the write transaction, all
  153. notification blocks registered on this specific `Realm` instance are called
  154. synchronously. Notification blocks for `Realm` instances on other threads
  155. and blocks registered for any Realm collection (including those on the
  156. current thread) are scheduled to be called synchronously.
  157. You can skip notifiying specific notification blocks about the changes made
  158. in this write transaction by passing in their associated notification
  159. tokens. This is primarily useful when the write transaction is saving
  160. changes already made in the UI and you do not want to have the notification
  161. block attempt to re-apply the same changes.
  162. The tokens passed to this function must be for notifications for this Realm
  163. which were added on the same thread as the write transaction is being
  164. performed on. Notifications for different threads cannot be skipped using
  165. this method.
  166. - warning: This method may only be called during a write transaction.
  167. - throws: An `NSError` if the transaction could not be written due to
  168. running out of disk space or other i/o errors.
  169. */
  170. public func commitWrite(withoutNotifying tokens: [NotificationToken] = []) throws {
  171. try rlmRealm.commitWriteTransactionWithoutNotifying(tokens)
  172. }
  173. /**
  174. Reverts all writes made in the current write transaction and ends the transaction.
  175. This rolls back all objects in the Realm to the state they were in at the
  176. beginning of the write transaction, and then ends the transaction.
  177. This restores the data for deleted objects, but does not revive invalidated
  178. object instances. Any `Object`s which were added to the Realm will be
  179. invalidated rather than becoming unmanaged.
  180. Given the following code:
  181. ```swift
  182. let oldObject = objects(ObjectType).first!
  183. let newObject = ObjectType()
  184. realm.beginWrite()
  185. realm.add(newObject)
  186. realm.delete(oldObject)
  187. realm.cancelWrite()
  188. ```
  189. Both `oldObject` and `newObject` will return `true` for `isInvalidated`,
  190. but re-running the query which provided `oldObject` will once again return
  191. the valid object.
  192. KVO observers on any objects which were modified during the transaction
  193. will be notified about the change back to their initial values, but no
  194. other notifcations are produced by a cancelled write transaction.
  195. - warning: This method may only be called during a write transaction.
  196. */
  197. public func cancelWrite() {
  198. rlmRealm.cancelWriteTransaction()
  199. }
  200. /**
  201. Indicates whether the Realm is currently in a write transaction.
  202. - warning: Do not simply check this property and then start a write transaction whenever an object needs to be
  203. created, updated, or removed. Doing so might cause a large number of write transactions to be created,
  204. degrading performance. Instead, always prefer performing multiple updates during a single transaction.
  205. */
  206. public var isInWriteTransaction: Bool {
  207. return rlmRealm.inWriteTransaction
  208. }
  209. // MARK: Adding and Creating objects
  210. /**
  211. Adds or updates an existing object into the Realm.
  212. Only pass `true` to `update` if the object has a primary key. If no object exists in the Realm with the same
  213. primary key value, the object is inserted. Otherwise, the existing object is updated with any changed values.
  214. When added, all child relationships referenced by this object will also be added to the Realm if they are not
  215. already in it. If the object or any related objects are already being managed by a different Realm an error will be
  216. thrown. Instead, use one of the `create` functions to insert a copy of a managed object into a different Realm.
  217. The object to be added must be valid and cannot have been previously deleted from a Realm (i.e. `isInvalidated`
  218. must be `false`).
  219. - parameter object: The object to be added to this Realm.
  220. - parameter update: If `true`, the Realm will try to find an existing copy of the object (with the same primary
  221. key), and update it. Otherwise, the object will be added.
  222. */
  223. public func add(_ object: Object, update: Bool = false) {
  224. if update && object.objectSchema.primaryKeyProperty == nil {
  225. throwRealmException("'\(object.objectSchema.className)' does not have a primary key and can not be updated")
  226. }
  227. RLMAddObjectToRealm(object, rlmRealm, update)
  228. }
  229. /**
  230. Adds or updates all the objects in a collection into the Realm.
  231. - see: `add(_:update:)`
  232. - warning: This method may only be called during a write transaction.
  233. - parameter objects: A sequence which contains objects to be added to the Realm.
  234. - parameter update: If `true`, objects that are already in the Realm will be updated instead of added anew.
  235. */
  236. public func add<S: Sequence>(_ objects: S, update: Bool = false) where S.Iterator.Element: Object {
  237. for obj in objects {
  238. add(obj, update: update)
  239. }
  240. }
  241. /**
  242. Creates or updates a Realm object with a given value, adding it to the Realm and returning it.
  243. You may only pass `true` to `update` if the object has a primary key. If no object exists
  244. in the Realm with the same primary key value, the object is inserted. Otherwise, the
  245. existing object is updated with any changed values.
  246. The `value` argument can be a Realm object, a key-value coding compliant object, an array
  247. or dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing
  248. one element for each managed property. Do not pass in a `LinkingObjects` instance, either
  249. by itself or as a member of a collection.
  250. If the object is being created, all required properties that were not defined with default
  251. values must be given initial values through the `value` argument. Otherwise, an Objective-C
  252. exception will be thrown.
  253. If the object is being updated, all properties defined in its schema will be set by copying
  254. from `value` using key-value coding. If the `value` argument does not respond to `value(forKey:)`
  255. for a given property name (or getter name, if defined), that value will remain untouched.
  256. Nullable properties on the object can be set to nil by using `NSNull` as the updated value,
  257. or (if you are passing in an instance of an `Object` subclass) setting the corresponding
  258. property on `value` to nil.
  259. If the `value` argument is an array, all properties must be present, valid and in the same
  260. order as the properties defined in the model.
  261. - warning: This method may only be called during a write transaction.
  262. - parameter type: The type of the object to create.
  263. - parameter value: The value used to populate the object.
  264. - parameter update: If `true`, the Realm will try to find an existing copy of the object (with the same primary
  265. key), and update it. Otherwise, the object will be added.
  266. - returns: The newly created object.
  267. */
  268. @discardableResult
  269. public func create<T: Object>(_ type: T.Type, value: Any = [:], update: Bool = false) -> T {
  270. let typeName = (type as Object.Type).className()
  271. if update && schema[typeName]?.primaryKeyProperty == nil {
  272. throwRealmException("'\(typeName)' does not have a primary key and can not be updated")
  273. }
  274. return unsafeDowncast(RLMCreateObjectInRealmWithValue(rlmRealm, typeName, value, update), to: T.self)
  275. }
  276. /**
  277. This method is useful only in specialized circumstances, for example, when building
  278. components that integrate with Realm. If you are simply building an app on Realm, it is
  279. recommended to use the typed method `create(_:value:update:)`.
  280. Creates or updates an object with the given class name and adds it to the `Realm`, populating
  281. the object with the given value.
  282. You may only pass `true` to `update` if the object has a primary key. If no object exists
  283. in the Realm with the same primary key value, the object is inserted. Otherwise, the
  284. existing object is updated with any changed values.
  285. The `value` argument can be a Realm object, a key-value coding compliant object, an array
  286. or dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing
  287. one element for each managed property. Do not pass in a `LinkingObjects` instance, either
  288. by itself or as a member of a collection.
  289. If the object is being created, all required properties that were not defined with default
  290. values must be given initial values through the `value` argument. Otherwise, an Objective-C
  291. exception will be thrown.
  292. If the object is being updated, all properties defined in its schema will be set by copying
  293. from `value` using key-value coding. If the `value` argument does not respond to `value(forKey:)`
  294. for a given property name (or getter name, if defined), that value will remain untouched.
  295. Nullable properties on the object can be set to nil by using `NSNull` as the updated value.
  296. If the `value` argument is an array, all properties must be present, valid and in the same
  297. order as the properties defined in the model.
  298. - warning: This method can only be called during a write transaction.
  299. - parameter className: The class name of the object to create.
  300. - parameter value: The value used to populate the object.
  301. - parameter update: If true will try to update existing objects with the same primary key.
  302. - returns: The created object.
  303. :nodoc:
  304. */
  305. @discardableResult
  306. public func dynamicCreate(_ typeName: String, value: Any = [:], update: Bool = false) -> DynamicObject {
  307. if update && schema[typeName]?.primaryKeyProperty == nil {
  308. throwRealmException("'\(typeName)' does not have a primary key and can not be updated")
  309. }
  310. return noWarnUnsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, typeName, value, update),
  311. to: DynamicObject.self)
  312. }
  313. // MARK: Deleting objects
  314. /**
  315. Deletes an object from the Realm. Once the object is deleted it is considered invalidated.
  316. - warning: This method may only be called during a write transaction.
  317. - parameter object: The object to be deleted.
  318. */
  319. public func delete(_ object: Object) {
  320. RLMDeleteObjectFromRealm(object, rlmRealm)
  321. }
  322. /**
  323. Deletes zero or more objects from the Realm.
  324. Do not pass in a slice to a `Results` or any other auto-updating Realm collection
  325. type (for example, the type returned by the Swift `suffix(_:)` standard library
  326. method). Instead, make a copy of the objects to delete using `Array()`, and pass
  327. that instead. Directly passing in a view into an auto-updating collection may
  328. result in 'index out of bounds' exceptions being thrown.
  329. - warning: This method may only be called during a write transaction.
  330. - parameter objects: The objects to be deleted. This can be a `List<Object>`,
  331. `Results<Object>`, or any other Swift `Sequence` whose
  332. elements are `Object`s (subject to the caveats above).
  333. */
  334. public func delete<S: Sequence>(_ objects: S) where S.Iterator.Element: Object {
  335. for obj in objects {
  336. delete(obj)
  337. }
  338. }
  339. /**
  340. Deletes zero or more objects from the Realm.
  341. - warning: This method may only be called during a write transaction.
  342. - parameter objects: A list of objects to delete.
  343. :nodoc:
  344. */
  345. public func delete<Element: Object>(_ objects: List<Element>) {
  346. rlmRealm.deleteObjects(objects._rlmArray)
  347. }
  348. /**
  349. Deletes zero or more objects from the Realm.
  350. - warning: This method may only be called during a write transaction.
  351. - parameter objects: A `Results` containing the objects to be deleted.
  352. :nodoc:
  353. */
  354. public func delete<Element: Object>(_ objects: Results<Element>) {
  355. rlmRealm.deleteObjects(objects.rlmResults)
  356. }
  357. /**
  358. Deletes all objects from the Realm.
  359. - warning: This method may only be called during a write transaction.
  360. */
  361. public func deleteAll() {
  362. RLMDeleteAllObjectsFromRealm(rlmRealm)
  363. }
  364. // MARK: Object Retrieval
  365. /**
  366. Returns all objects of the given type stored in the Realm.
  367. - parameter type: The type of the objects to be returned.
  368. - returns: A `Results` containing the objects.
  369. */
  370. public func objects<Element: Object>(_ type: Element.Type) -> Results<Element> {
  371. return Results(RLMGetObjects(rlmRealm, type.className(), nil))
  372. }
  373. /**
  374. This method is useful only in specialized circumstances, for example, when building
  375. components that integrate with Realm. If you are simply building an app on Realm, it is
  376. recommended to use the typed method `objects(type:)`.
  377. Returns all objects for a given class name in the Realm.
  378. - parameter typeName: The class name of the objects to be returned.
  379. - returns: All objects for the given class name as dynamic objects
  380. :nodoc:
  381. */
  382. public func dynamicObjects(_ typeName: String) -> Results<DynamicObject> {
  383. return Results<DynamicObject>(RLMGetObjects(rlmRealm, typeName, nil))
  384. }
  385. /**
  386. Retrieves the single instance of a given object type with the given primary key from the Realm.
  387. This method requires that `primaryKey()` be overridden on the given object class.
  388. - see: `Object.primaryKey()`
  389. - parameter type: The type of the object to be returned.
  390. - parameter key: The primary key of the desired object.
  391. - returns: An object of type `type`, or `nil` if no instance with the given primary key exists.
  392. */
  393. public func object<Element: Object, KeyType>(ofType type: Element.Type, forPrimaryKey key: KeyType) -> Element? {
  394. return unsafeBitCast(RLMGetObject(rlmRealm, (type as Object.Type).className(),
  395. dynamicBridgeCast(fromSwift: key)) as! RLMObjectBase?,
  396. to: Optional<Element>.self)
  397. }
  398. /**
  399. This method is useful only in specialized circumstances, for example, when building
  400. components that integrate with Realm. If you are simply building an app on Realm, it is
  401. recommended to use the typed method `objectForPrimaryKey(_:key:)`.
  402. Get a dynamic object with the given class name and primary key.
  403. Returns `nil` if no object exists with the given class name and primary key.
  404. This method requires that `primaryKey()` be overridden on the given subclass.
  405. - see: Object.primaryKey()
  406. - warning: This method is useful only in specialized circumstances.
  407. - parameter className: The class name of the object to be returned.
  408. - parameter key: The primary key of the desired object.
  409. - returns: An object of type `DynamicObject` or `nil` if an object with the given primary key does not exist.
  410. :nodoc:
  411. */
  412. public func dynamicObject(ofType typeName: String, forPrimaryKey key: Any) -> DynamicObject? {
  413. return unsafeBitCast(RLMGetObject(rlmRealm, typeName, key) as! RLMObjectBase?, to: Optional<DynamicObject>.self)
  414. }
  415. // MARK: Notifications
  416. /**
  417. Adds a notification handler for changes made to this Realm, and returns a notification token.
  418. Notification handlers are called after each write transaction is committed, independent of the thread or process.
  419. Handler blocks are called on the same thread that they were added on, and may only be added on threads which are
  420. currently within a run loop. Unless you are specifically creating and running a run loop on a background thread,
  421. this will normally only be the main thread.
  422. Notifications can't be delivered as long as the run loop is blocked by other activity. When notifications can't be
  423. delivered instantly, multiple notifications may be coalesced.
  424. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
  425. updates, call `invalidate()` on the token.
  426. - parameter block: A block which is called to process Realm notifications. It receives the following parameters:
  427. `notification`: the incoming notification; `realm`: the Realm for which the notification
  428. occurred.
  429. - returns: A token which must be held for as long as you wish to continue receiving change notifications.
  430. */
  431. public func observe(_ block: @escaping NotificationBlock) -> NotificationToken {
  432. return rlmRealm.addNotificationBlock { rlmNotification, _ in
  433. switch rlmNotification {
  434. case RLMNotification.DidChange:
  435. block(.didChange, self)
  436. case RLMNotification.RefreshRequired:
  437. block(.refreshRequired, self)
  438. default:
  439. fatalError("Unhandled notification type: \(rlmNotification)")
  440. }
  441. }
  442. }
  443. // MARK: Autorefresh and Refresh
  444. /**
  445. Set this property to `true` to automatically update this Realm when changes happen in other threads.
  446. If set to `true` (the default), changes made on other threads will be reflected in this Realm on the next cycle of
  447. the run loop after the changes are committed. If set to `false`, you must manually call `refresh()` on the Realm
  448. to update it to get the latest data.
  449. Note that by default, background threads do not have an active run loop and you will need to manually call
  450. `refresh()` in order to update to the latest version, even if `autorefresh` is set to `true`.
  451. Even with this property enabled, you can still call `refresh()` at any time to update the Realm before the
  452. automatic refresh would occur.
  453. Notifications are sent when a write transaction is committed whether or not automatic refreshing is enabled.
  454. Disabling `autorefresh` on a `Realm` without any strong references to it will not have any effect, and
  455. `autorefresh` will revert back to `true` the next time the Realm is created. This is normally irrelevant as it
  456. means that there is nothing to refresh (as managed `Object`s, `List`s, and `Results` have strong references to the
  457. `Realm` that manages them), but it means that setting `autorefresh = false` in
  458. `application(_:didFinishLaunchingWithOptions:)` and only later storing Realm objects will not work.
  459. Defaults to `true`.
  460. */
  461. public var autorefresh: Bool {
  462. get {
  463. return rlmRealm.autorefresh
  464. }
  465. set {
  466. rlmRealm.autorefresh = newValue
  467. }
  468. }
  469. /**
  470. Updates the Realm and outstanding objects managed by the Realm to point to the most recent data.
  471. - returns: Whether there were any updates for the Realm. Note that `true` may be returned even if no data actually
  472. changed.
  473. */
  474. @discardableResult
  475. public func refresh() -> Bool {
  476. return rlmRealm.refresh()
  477. }
  478. // MARK: Invalidation
  479. /**
  480. Invalidates all `Object`s, `Results`, `LinkingObjects`, and `List`s managed by the Realm.
  481. A Realm holds a read lock on the version of the data accessed by it, so
  482. that changes made to the Realm on different threads do not modify or delete the
  483. data seen by this Realm. Calling this method releases the read lock,
  484. allowing the space used on disk to be reused by later write transactions rather
  485. than growing the file. This method should be called before performing long
  486. blocking operations on a background thread on which you previously read data
  487. from the Realm which you no longer need.
  488. All `Object`, `Results` and `List` instances obtained from this `Realm` instance on the current thread are
  489. invalidated. `Object`s and `Array`s cannot be used. `Results` will become empty. The Realm itself remains valid,
  490. and a new read transaction is implicitly begun the next time data is read from the Realm.
  491. Calling this method multiple times in a row without reading any data from the
  492. Realm, or before ever reading any data from the Realm, is a no-op. This method
  493. may not be called on a read-only Realm.
  494. */
  495. public func invalidate() {
  496. rlmRealm.invalidate()
  497. }
  498. // MARK: Writing a Copy
  499. /**
  500. Writes a compacted and optionally encrypted copy of the Realm to the given local URL.
  501. The destination file cannot already exist.
  502. Note that if this method is called from within a write transaction, the *current* data is written, not the data
  503. from the point when the previous write transaction was committed.
  504. - parameter fileURL: Local URL to save the Realm to.
  505. - parameter encryptionKey: Optional 64-byte encryption key to encrypt the new file with.
  506. - throws: An `NSError` if the copy could not be written.
  507. */
  508. public func writeCopy(toFile fileURL: URL, encryptionKey: Data? = nil) throws {
  509. try rlmRealm.writeCopy(to: fileURL, encryptionKey: encryptionKey)
  510. }
  511. // MARK: Internal
  512. internal var rlmRealm: RLMRealm
  513. internal init(_ rlmRealm: RLMRealm) {
  514. self.rlmRealm = rlmRealm
  515. }
  516. }
  517. // MARK: Equatable
  518. extension Realm: Equatable {
  519. /// Returns whether two `Realm` instances are equal.
  520. public static func == (lhs: Realm, rhs: Realm) -> Bool {
  521. return lhs.rlmRealm == rhs.rlmRealm
  522. }
  523. }
  524. // MARK: Notifications
  525. extension Realm {
  526. /// A notification indicating that changes were made to a Realm.
  527. public enum Notification: String {
  528. /**
  529. This notification is posted when the data in a Realm has changed.
  530. `didChange` is posted after a Realm has been refreshed to reflect a write transaction, This can happen when an
  531. autorefresh occurs, `refresh()` is called, after an implicit refresh from `write(_:)`/`beginWrite()`, or after
  532. a local write transaction is committed.
  533. */
  534. case didChange = "RLMRealmDidChangeNotification"
  535. /**
  536. This notification is posted when a write transaction has been committed to a Realm on a different thread for
  537. the same file.
  538. It is not posted if `autorefresh` is enabled, or if the Realm is refreshed before the notification has a chance
  539. to run.
  540. Realms with autorefresh disabled should normally install a handler for this notification which calls
  541. `refresh()` after doing some work. Refreshing the Realm is optional, but not refreshing the Realm may lead to
  542. large Realm files. This is because an extra copy of the data must be kept for the stale Realm.
  543. */
  544. case refreshRequired = "RLMRealmRefreshRequiredNotification"
  545. }
  546. }
  547. /// The type of a block to run for notification purposes when the data in a Realm is modified.
  548. public typealias NotificationBlock = (_ notification: Realm.Notification, _ realm: Realm) -> Void