Realm.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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 struct 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 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 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 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. - returns: A task object which can be used to observe or cancel the async open.
  89. - note: The returned Realm is confined to the thread on which it was created.
  90. Because GCD does not guarantee that queues will always use the same
  91. thread, accessing the returned Realm outside the callback block (even if
  92. accessed from `callbackQueue`) is unsafe.
  93. */
  94. @discardableResult
  95. public static func asyncOpen(configuration: Realm.Configuration = .defaultConfiguration,
  96. callbackQueue: DispatchQueue = .main,
  97. callback: @escaping (Realm?, Swift.Error?) -> Void) -> AsyncOpenTask {
  98. return AsyncOpenTask(rlmTask: RLMRealm.asyncOpen(with: configuration.rlmConfiguration, callbackQueue: callbackQueue) { rlmRealm, error in
  99. callback(rlmRealm.flatMap(Realm.init), error)
  100. })
  101. }
  102. /**
  103. A task object which can be used to observe or cancel an async open.
  104. When a synchronized Realm is opened asynchronously, the latest state of the
  105. Realm is downloaded from the server before the completion callback is
  106. invoked. This task object can be used to observe the state of the download
  107. or to cancel it. This should be used instead of trying to observe the
  108. download via the sync session as the sync session itself is created
  109. asynchronously, and may not exist yet when Realm.asyncOpen() returns.
  110. */
  111. public struct AsyncOpenTask {
  112. fileprivate let rlmTask: RLMAsyncOpenTask
  113. /**
  114. Cancel the asynchronous open.
  115. Any download in progress will be cancelled, and the completion block for this
  116. async open will never be called. If multiple async opens on the same Realm are
  117. happening concurrently, all other opens will fail with the error "operation cancelled".
  118. */
  119. public func cancel() { rlmTask.cancel() }
  120. /**
  121. Register a progress notification block.
  122. Each registered progress notification block is called whenever the sync
  123. subsystem has new progress data to report until the task is either cancelled
  124. or the completion callback is called. Progress notifications are delivered on
  125. the supplied queue.
  126. - parameter queue: The queue to deliver progress notifications on.
  127. - parameter block: The block to invoke when notifications are available.
  128. */
  129. public func addProgressNotification(queue: DispatchQueue = .main,
  130. block: @escaping (SyncSession.Progress) -> Void) {
  131. rlmTask.addProgressNotification(on: queue) { transferred, transferrable in
  132. block(SyncSession.Progress(transferred: transferred, transferrable: transferrable))
  133. }
  134. }
  135. }
  136. // MARK: Transactions
  137. /**
  138. Performs actions contained within the given block inside a write transaction.
  139. If the block throws an error, the transaction will be canceled and any
  140. changes made before the error will be rolled back.
  141. Only one write transaction can be open at a time for each Realm file. Write
  142. transactions cannot be nested, and trying to begin a write transaction on a
  143. Realm which is already in a write transaction will throw an exception.
  144. Calls to `write` from `Realm` instances for the same Realm file in other
  145. threads or other processes will block until the current write transaction
  146. completes or is cancelled.
  147. Before beginning the write transaction, `write` updates the `Realm`
  148. instance to the latest Realm version, as if `refresh()` had been called,
  149. and generates notifications if applicable. This has no effect if the Realm
  150. was already up to date.
  151. You can skip notifiying specific notification blocks about the changes made
  152. in this write transaction by passing in their associated notification
  153. tokens. This is primarily useful when the write transaction is saving
  154. changes already made in the UI and you do not want to have the notification
  155. block attempt to re-apply the same changes.
  156. The tokens passed to this function must be for notifications for this Realm
  157. which were added on the same thread as the write transaction is being
  158. performed on. Notifications for different threads cannot be skipped using
  159. this method.
  160. - parameter tokens: An array of notification tokens which were returned
  161. from adding callbacks which you do not want to be
  162. notified for the changes made in this write transaction.
  163. - parameter block: The block containing actions to perform.
  164. - returns: The value returned from the block, if any.
  165. - throws: An `NSError` if the transaction could not be completed successfully.
  166. If `block` throws, the function throws the propagated `ErrorType` instead.
  167. */
  168. @discardableResult
  169. public func write<Result>(withoutNotifying tokens: [NotificationToken] = [], _ block: (() throws -> Result)) throws -> Result {
  170. beginWrite()
  171. var ret: Result!
  172. do {
  173. ret = try block()
  174. } catch let error {
  175. if isInWriteTransaction { cancelWrite() }
  176. throw error
  177. }
  178. if isInWriteTransaction { try commitWrite(withoutNotifying: tokens) }
  179. return ret
  180. }
  181. /**
  182. Begins a write transaction on the Realm.
  183. Only one write transaction can be open at a time for each Realm file. Write
  184. transactions cannot be nested, and trying to begin a write transaction on a
  185. Realm which is already in a write transaction will throw an exception.
  186. Calls to `beginWrite` from `Realm` instances for the same Realm file in
  187. other threads or other processes will block until the current write
  188. transaction completes or is cancelled.
  189. Before beginning the write transaction, `beginWrite` updates the `Realm`
  190. instance to the latest Realm version, as if `refresh()` had been called,
  191. and generates notifications if applicable. This has no effect if the Realm
  192. was already up to date.
  193. It is rarely a good idea to have write transactions span multiple cycles of
  194. the run loop, but if you do wish to do so you will need to ensure that the
  195. Realm participating in the write transaction is kept alive until the write
  196. transaction is committed.
  197. */
  198. public func beginWrite() {
  199. rlmRealm.beginWriteTransaction()
  200. }
  201. /**
  202. Commits all write operations in the current write transaction, and ends
  203. the transaction.
  204. After saving the changes and completing the write transaction, all
  205. notification blocks registered on this specific `Realm` instance are called
  206. synchronously. Notification blocks for `Realm` instances on other threads
  207. and blocks registered for any Realm collection (including those on the
  208. current thread) are scheduled to be called synchronously.
  209. You can skip notifiying specific notification blocks about the changes made
  210. in this write transaction by passing in their associated notification
  211. tokens. This is primarily useful when the write transaction is saving
  212. changes already made in the UI and you do not want to have the notification
  213. block attempt to re-apply the same changes.
  214. The tokens passed to this function must be for notifications for this Realm
  215. which were added on the same thread as the write transaction is being
  216. performed on. Notifications for different threads cannot be skipped using
  217. this method.
  218. - warning: This method may only be called during a write transaction.
  219. - parameter tokens: An array of notification tokens which were returned
  220. from adding callbacks which you do not want to be
  221. notified for the changes made in this write transaction.
  222. - throws: An `NSError` if the transaction could not be written due to
  223. running out of disk space or other i/o errors.
  224. */
  225. public func commitWrite(withoutNotifying tokens: [NotificationToken] = []) throws {
  226. try rlmRealm.commitWriteTransactionWithoutNotifying(tokens)
  227. }
  228. /**
  229. Reverts all writes made in the current write transaction and ends the transaction.
  230. This rolls back all objects in the Realm to the state they were in at the
  231. beginning of the write transaction, and then ends the transaction.
  232. This restores the data for deleted objects, but does not revive invalidated
  233. object instances. Any `Object`s which were added to the Realm will be
  234. invalidated rather than becoming unmanaged.
  235. Given the following code:
  236. ```swift
  237. let oldObject = objects(ObjectType).first!
  238. let newObject = ObjectType()
  239. realm.beginWrite()
  240. realm.add(newObject)
  241. realm.delete(oldObject)
  242. realm.cancelWrite()
  243. ```
  244. Both `oldObject` and `newObject` will return `true` for `isInvalidated`,
  245. but re-running the query which provided `oldObject` will once again return
  246. the valid object.
  247. KVO observers on any objects which were modified during the transaction
  248. will be notified about the change back to their initial values, but no
  249. other notifcations are produced by a cancelled write transaction.
  250. - warning: This method may only be called during a write transaction.
  251. */
  252. public func cancelWrite() {
  253. rlmRealm.cancelWriteTransaction()
  254. }
  255. /**
  256. Indicates whether the Realm is currently in a write transaction.
  257. - warning: Do not simply check this property and then start a write transaction whenever an object needs to be
  258. created, updated, or removed. Doing so might cause a large number of write transactions to be created,
  259. degrading performance. Instead, always prefer performing multiple updates during a single transaction.
  260. */
  261. public var isInWriteTransaction: Bool {
  262. return rlmRealm.inWriteTransaction
  263. }
  264. // MARK: Adding and Creating objects
  265. /**
  266. What to do when an object being added to or created in a Realm has a primary key that already exists.
  267. */
  268. public enum UpdatePolicy: Int {
  269. /**
  270. Throw an exception. This is the default when no policy is specified for `add()` or `create()`.
  271. This behavior is the same as passing `update: false` to `add()` or `create()`.
  272. */
  273. case error = 1
  274. /**
  275. Overwrite only properties in the existing object which are different from the new values. This results
  276. in change notifications reporting only the properties which changed, and influences the sync merge logic.
  277. If few or no of the properties are changing this will be faster than .all and reduce how much data has
  278. to be written to the Realm file. If all of the properties are changing, it may be slower than .all (but
  279. will never result in *more* data being written).
  280. */
  281. case modified = 3
  282. /**
  283. Overwrite all properties in the existing object with the new values, even if they have not changed. This
  284. results in change notifications reporting all properties as changed, and influences the sync merge logic.
  285. This behavior is the same as passing `update: true` to `add()` or `create()`.
  286. */
  287. case all = 2
  288. }
  289. /// :nodoc:
  290. @available(*, unavailable, message: "Pass .error, .modified or .all rather than a boolean. .error is equivalent to false and .all is equivalent to true.")
  291. public func add(_ object: Object, update: Bool) {
  292. fatalError()
  293. }
  294. /**
  295. Adds an unmanaged object to this Realm.
  296. If an object with the same primary key already exists in this Realm, it is updated with the property values from
  297. this object as specified by the `UpdatePolicy` selected. The update policy must be `.error` for objects with no
  298. primary key.
  299. Adding an object to a Realm will also add all child relationships referenced by that object (via `Object` and
  300. `List<Object>` properties). Those objects must also be valid objects to add to this Realm, and the value of
  301. the `update:` parameter is propagated to those adds.
  302. The object to be added must either be an unmanaged object or a valid object which is already managed by this
  303. Realm. Adding an object already managed by this Realm is a no-op, while adding an object which is managed by
  304. another Realm or which has been deleted from any Realm (i.e. one where `isInvalidated` is `true`) is an error.
  305. To copy a managed object from one Realm to another, use `create()` instead.
  306. - warning: This method may only be called during a write transaction.
  307. - parameter object: The object to be added to this Realm.
  308. - parameter update: What to do if an object with the same primary key alredy exists. Must be `.error` for objects
  309. without a primary key.
  310. */
  311. public func add(_ object: Object, update: UpdatePolicy = .error) {
  312. if update != .error && object.objectSchema.primaryKeyProperty == nil {
  313. throwRealmException("'\(object.objectSchema.className)' does not have a primary key and can not be updated")
  314. }
  315. RLMAddObjectToRealm(object, rlmRealm, RLMUpdatePolicy(rawValue: UInt(update.rawValue))!)
  316. }
  317. /// :nodoc:
  318. @available(*, unavailable, message: "Pass .error, .modified or .all rather than a boolean. .error is equivalent to false and .all is equivalent to true.")
  319. public func add<S: Sequence>(_ objects: S, update: Bool) where S.Iterator.Element: Object {
  320. fatalError()
  321. }
  322. /**
  323. Adds all the objects in a collection into the Realm.
  324. - see: `add(_:update:)`
  325. - warning: This method may only be called during a write transaction.
  326. - parameter objects: A sequence which contains objects to be added to the Realm.
  327. - parameter update: How to handle
  328. without a primary key.
  329. - parameter update: How to handle objects in the collection with a primary key that alredy exists in this
  330. Realm. Must be `.error` for object types without a primary key.
  331. */
  332. public func add<S: Sequence>(_ objects: S, update: UpdatePolicy = .error) where S.Iterator.Element: Object {
  333. for obj in objects {
  334. add(obj, update: update)
  335. }
  336. }
  337. /// :nodoc:
  338. @discardableResult
  339. @available(*, unavailable, message: "Pass .error, .modified or .all rather than a boolean. .error is equivalent to false and .all is equivalent to true.")
  340. public func create<T: Object>(_ type: T.Type, value: Any = [:], update: Bool) -> T {
  341. fatalError()
  342. }
  343. /**
  344. Creates a Realm object with a given value, adding it to the Realm and returning it.
  345. The `value` argument can be a Realm object, a key-value coding compliant object, an array
  346. or dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing
  347. one element for each managed property. Do not pass in a `LinkingObjects` instance, either
  348. by itself or as a member of a collection. If the `value` argument is an array, all properties
  349. must be present, valid and in the same order as the properties defined in the model.
  350. If the object type does not have a primary key or no object with the specified primary key
  351. already exists, a new object is created in the Realm. If an object already exists in the Realm
  352. with the specified primary key and the update policy is `.modified` or `.all`, the existing
  353. object will be updated and a reference to that object will be returned.
  354. If the object is being updated, all properties defined in its schema will be set by copying
  355. from `value` using key-value coding. If the `value` argument does not respond to `value(forKey:)`
  356. for a given property name (or getter name, if defined), that value will remain untouched.
  357. Nullable properties on the object can be set to nil by using `NSNull` as the updated value,
  358. or (if you are passing in an instance of an `Object` subclass) setting the corresponding
  359. property on `value` to nil.
  360. - warning: This method may only be called during a write transaction.
  361. - parameter type: The type of the object to create.
  362. - parameter value: The value used to populate the object.
  363. - parameter update: What to do if an object with the same primary key alredy exists. Must be `.error` for object
  364. types without a primary key.
  365. - returns: The newly created object.
  366. */
  367. @discardableResult
  368. public func create<T: Object>(_ type: T.Type, value: Any = [:], update: UpdatePolicy = .error) -> T {
  369. if update != .error {
  370. RLMVerifyHasPrimaryKey(type)
  371. }
  372. let typeName = (type as Object.Type).className()
  373. return unsafeDowncast(RLMCreateObjectInRealmWithValue(rlmRealm, typeName, value,
  374. RLMUpdatePolicy(rawValue: UInt(update.rawValue))!), to: type)
  375. }
  376. /// :nodoc:
  377. @discardableResult
  378. @available(*, unavailable, message: "Pass .error, .modified or .all rather than a boolean. .error is equivalent to false and .all is equivalent to true.")
  379. public func dynamicCreate(_ typeName: String, value: Any = [:], update: Bool) -> DynamicObject {
  380. fatalError()
  381. }
  382. /**
  383. This method is useful only in specialized circumstances, for example, when building
  384. components that integrate with Realm. If you are simply building an app on Realm, it is
  385. recommended to use the typed method `create(_:value:update:)`.
  386. Creates or updates an object with the given class name and adds it to the `Realm`, populating
  387. the object with the given value.
  388. The `value` argument can be a Realm object, a key-value coding compliant object, an array
  389. or dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing
  390. one element for each managed property. Do not pass in a `LinkingObjects` instance, either
  391. by itself or as a member of a collection. If the `value` argument is an array, all properties
  392. must be present, valid and in the same order as the properties defined in the model.
  393. If the object type does not have a primary key or no object with the specified primary key
  394. already exists, a new object is created in the Realm. If an object already exists in the Realm
  395. with the specified primary key and the update policy is `.modified` or `.all`, the existing
  396. object will be updated and a reference to that object will be returned.
  397. If the object is being updated, all properties defined in its schema will be set by copying
  398. from `value` using key-value coding. If the `value` argument does not respond to `value(forKey:)`
  399. for a given property name (or getter name, if defined), that value will remain untouched.
  400. Nullable properties on the object can be set to nil by using `NSNull` as the updated value,
  401. or (if you are passing in an instance of an `Object` subclass) setting the corresponding
  402. property on `value` to nil.
  403. - warning: This method can only be called during a write transaction.
  404. - parameter className: The class name of the object to create.
  405. - parameter value: The value used to populate the object.
  406. - parameter update: What to do if an object with the same primary key alredy exists.
  407. Must be `.error` for object types without a primary key.
  408. - returns: The created object.
  409. :nodoc:
  410. */
  411. @discardableResult
  412. public func dynamicCreate(_ typeName: String, value: Any = [:], update: UpdatePolicy = .error) -> DynamicObject {
  413. if update != .error && schema[typeName]?.primaryKeyProperty == nil {
  414. throwRealmException("'\(typeName)' does not have a primary key and can not be updated")
  415. }
  416. return noWarnUnsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, typeName, value,
  417. RLMUpdatePolicy(rawValue: UInt(update.rawValue))!),
  418. to: DynamicObject.self)
  419. }
  420. // MARK: Deleting objects
  421. /**
  422. Deletes an object from the Realm. Once the object is deleted it is considered invalidated.
  423. - warning: This method may only be called during a write transaction.
  424. - parameter object: The object to be deleted.
  425. */
  426. public func delete(_ object: Object) {
  427. RLMDeleteObjectFromRealm(object, rlmRealm)
  428. }
  429. /**
  430. Deletes zero or more objects from the Realm.
  431. Do not pass in a slice to a `Results` or any other auto-updating Realm collection
  432. type (for example, the type returned by the Swift `suffix(_:)` standard library
  433. method). Instead, make a copy of the objects to delete using `Array()`, and pass
  434. that instead. Directly passing in a view into an auto-updating collection may
  435. result in 'index out of bounds' exceptions being thrown.
  436. - warning: This method may only be called during a write transaction.
  437. - parameter objects: The objects to be deleted. This can be a `List<Object>`,
  438. `Results<Object>`, or any other Swift `Sequence` whose
  439. elements are `Object`s (subject to the caveats above).
  440. */
  441. public func delete<S: Sequence>(_ objects: S) where S.Iterator.Element: Object {
  442. for obj in objects {
  443. delete(obj)
  444. }
  445. }
  446. /**
  447. Deletes zero or more objects from the Realm.
  448. - warning: This method may only be called during a write transaction.
  449. - parameter objects: A list of objects to delete.
  450. :nodoc:
  451. */
  452. public func delete<Element: Object>(_ objects: List<Element>) {
  453. rlmRealm.deleteObjects(objects._rlmArray)
  454. }
  455. /**
  456. Deletes zero or more objects from the Realm.
  457. - warning: This method may only be called during a write transaction.
  458. - parameter objects: A `Results` containing the objects to be deleted.
  459. :nodoc:
  460. */
  461. public func delete<Element: Object>(_ objects: Results<Element>) {
  462. rlmRealm.deleteObjects(objects.rlmResults)
  463. }
  464. /**
  465. Deletes all objects from the Realm.
  466. - warning: This method may only be called during a write transaction.
  467. */
  468. public func deleteAll() {
  469. RLMDeleteAllObjectsFromRealm(rlmRealm)
  470. }
  471. // MARK: Object Retrieval
  472. /**
  473. Returns all objects of the given type stored in the Realm.
  474. - parameter type: The type of the objects to be returned.
  475. - returns: A `Results` containing the objects.
  476. */
  477. public func objects<Element: Object>(_ type: Element.Type) -> Results<Element> {
  478. return Results(RLMGetObjects(rlmRealm, type.className(), nil))
  479. }
  480. /**
  481. This method is useful only in specialized circumstances, for example, when building
  482. components that integrate with Realm. If you are simply building an app on Realm, it is
  483. recommended to use the typed method `objects(type:)`.
  484. Returns all objects for a given class name in the Realm.
  485. - parameter typeName: The class name of the objects to be returned.
  486. - returns: All objects for the given class name as dynamic objects
  487. :nodoc:
  488. */
  489. public func dynamicObjects(_ typeName: String) -> Results<DynamicObject> {
  490. return Results<DynamicObject>(RLMGetObjects(rlmRealm, typeName, nil))
  491. }
  492. /**
  493. Retrieves the single instance of a given object type with the given primary key from the Realm.
  494. This method requires that `primaryKey()` be overridden on the given object class.
  495. - see: `Object.primaryKey()`
  496. - parameter type: The type of the object to be returned.
  497. - parameter key: The primary key of the desired object.
  498. - returns: An object of type `type`, or `nil` if no instance with the given primary key exists.
  499. */
  500. public func object<Element: Object, KeyType>(ofType type: Element.Type, forPrimaryKey key: KeyType) -> Element? {
  501. return unsafeBitCast(RLMGetObject(rlmRealm, (type as Object.Type).className(),
  502. dynamicBridgeCast(fromSwift: key)) as! RLMObjectBase?,
  503. to: Optional<Element>.self)
  504. }
  505. /**
  506. This method is useful only in specialized circumstances, for example, when building
  507. components that integrate with Realm. If you are simply building an app on Realm, it is
  508. recommended to use the typed method `objectForPrimaryKey(_:key:)`.
  509. Get a dynamic object with the given class name and primary key.
  510. Returns `nil` if no object exists with the given class name and primary key.
  511. This method requires that `primaryKey()` be overridden on the given subclass.
  512. - see: Object.primaryKey()
  513. - warning: This method is useful only in specialized circumstances.
  514. - parameter className: The class name of the object to be returned.
  515. - parameter key: The primary key of the desired object.
  516. - returns: An object of type `DynamicObject` or `nil` if an object with the given primary key does not exist.
  517. :nodoc:
  518. */
  519. public func dynamicObject(ofType typeName: String, forPrimaryKey key: Any) -> DynamicObject? {
  520. return unsafeBitCast(RLMGetObject(rlmRealm, typeName, key) as! RLMObjectBase?, to: Optional<DynamicObject>.self)
  521. }
  522. // MARK: Notifications
  523. /**
  524. Adds a notification handler for changes made to this Realm, and returns a notification token.
  525. Notification handlers are called after each write transaction is committed, independent of the thread or process.
  526. Handler blocks are called on the same thread that they were added on, and may only be added on threads which are
  527. currently within a run loop. Unless you are specifically creating and running a run loop on a background thread,
  528. this will normally only be the main thread.
  529. Notifications can't be delivered as long as the run loop is blocked by other activity. When notifications can't be
  530. delivered instantly, multiple notifications may be coalesced.
  531. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
  532. updates, call `invalidate()` on the token.
  533. - parameter block: A block which is called to process Realm notifications. It receives the following parameters:
  534. `notification`: the incoming notification; `realm`: the Realm for which the notification
  535. occurred.
  536. - returns: A token which must be held for as long as you wish to continue receiving change notifications.
  537. */
  538. public func observe(_ block: @escaping NotificationBlock) -> NotificationToken {
  539. return rlmRealm.addNotificationBlock { rlmNotification, _ in
  540. switch rlmNotification {
  541. case RLMNotification.DidChange:
  542. block(.didChange, self)
  543. case RLMNotification.RefreshRequired:
  544. block(.refreshRequired, self)
  545. default:
  546. fatalError("Unhandled notification type: \(rlmNotification)")
  547. }
  548. }
  549. }
  550. // MARK: Autorefresh and Refresh
  551. /**
  552. Set this property to `true` to automatically update this Realm when changes happen in other threads.
  553. If set to `true` (the default), changes made on other threads will be reflected in this Realm on the next cycle of
  554. the run loop after the changes are committed. If set to `false`, you must manually call `refresh()` on the Realm
  555. to update it to get the latest data.
  556. Note that by default, background threads do not have an active run loop and you will need to manually call
  557. `refresh()` in order to update to the latest version, even if `autorefresh` is set to `true`.
  558. Even with this property enabled, you can still call `refresh()` at any time to update the Realm before the
  559. automatic refresh would occur.
  560. Notifications are sent when a write transaction is committed whether or not automatic refreshing is enabled.
  561. Disabling `autorefresh` on a `Realm` without any strong references to it will not have any effect, and
  562. `autorefresh` will revert back to `true` the next time the Realm is created. This is normally irrelevant as it
  563. means that there is nothing to refresh (as managed `Object`s, `List`s, and `Results` have strong references to the
  564. `Realm` that manages them), but it means that setting `autorefresh = false` in
  565. `application(_:didFinishLaunchingWithOptions:)` and only later storing Realm objects will not work.
  566. Defaults to `true`.
  567. */
  568. public var autorefresh: Bool {
  569. get {
  570. return rlmRealm.autorefresh
  571. }
  572. nonmutating set {
  573. rlmRealm.autorefresh = newValue
  574. }
  575. }
  576. /**
  577. Updates the Realm and outstanding objects managed by the Realm to point to the most recent data.
  578. - returns: Whether there were any updates for the Realm. Note that `true` may be returned even if no data actually
  579. changed.
  580. */
  581. @discardableResult
  582. public func refresh() -> Bool {
  583. return rlmRealm.refresh()
  584. }
  585. // MARK: Invalidation
  586. /**
  587. Invalidates all `Object`s, `Results`, `LinkingObjects`, and `List`s managed by the Realm.
  588. A Realm holds a read lock on the version of the data accessed by it, so
  589. that changes made to the Realm on different threads do not modify or delete the
  590. data seen by this Realm. Calling this method releases the read lock,
  591. allowing the space used on disk to be reused by later write transactions rather
  592. than growing the file. This method should be called before performing long
  593. blocking operations on a background thread on which you previously read data
  594. from the Realm which you no longer need.
  595. All `Object`, `Results` and `List` instances obtained from this `Realm` instance on the current thread are
  596. invalidated. `Object`s and `Array`s cannot be used. `Results` will become empty. The Realm itself remains valid,
  597. and a new read transaction is implicitly begun the next time data is read from the Realm.
  598. Calling this method multiple times in a row without reading any data from the
  599. Realm, or before ever reading any data from the Realm, is a no-op. This method
  600. may not be called on a read-only Realm.
  601. */
  602. public func invalidate() {
  603. rlmRealm.invalidate()
  604. }
  605. // MARK: File Management
  606. /**
  607. Writes a compacted and optionally encrypted copy of the Realm to the given local URL.
  608. The destination file cannot already exist.
  609. Note that if this method is called from within a write transaction, the *current* data is written, not the data
  610. from the point when the previous write transaction was committed.
  611. - parameter fileURL: Local URL to save the Realm to.
  612. - parameter encryptionKey: Optional 64-byte encryption key to encrypt the new file with.
  613. - throws: An `NSError` if the copy could not be written.
  614. */
  615. public func writeCopy(toFile fileURL: URL, encryptionKey: Data? = nil) throws {
  616. try rlmRealm.writeCopy(to: fileURL, encryptionKey: encryptionKey)
  617. }
  618. /**
  619. Checks if the Realm file for the given configuration exists locally on disk.
  620. For non-synchronized, non-in-memory Realms, this is equivalent to
  621. `FileManager.default.fileExists(atPath:)`. For synchronized Realms, it
  622. takes care of computing the actual path on disk based on the server,
  623. virtual path, and user as is done when opening the Realm.
  624. @param config A Realm configuration to check the existence of.
  625. @return true if the Realm file for the given configuration exists on disk, false otherwise.
  626. */
  627. public static func fileExists(for config: Configuration) -> Bool {
  628. return RLMRealm.fileExists(for: config.rlmConfiguration)
  629. }
  630. /**
  631. Deletes the local Realm file and associated temporary files for the given configuration.
  632. This deletes the ".realm", ".note" and ".management" files which would be
  633. created by opening the Realm with the given configuration. It does not
  634. delete the ".lock" file (which contains no persisted data and is recreated
  635. from scratch every time the Realm file is opened).
  636. The Realm must not be currently open on any thread or in another process.
  637. If it is, this will throw the error .alreadyOpen. Attempting to open the
  638. Realm on another thread while the deletion is happening will block, and
  639. then create a new Realm and open that afterwards.
  640. If the Realm already does not exist this will return `false`.
  641. @param config A Realm configuration identifying the Realm to be deleted.
  642. @return true if any files were deleted, false otherwise.
  643. */
  644. public static func deleteFiles(for config: Configuration) throws -> Bool {
  645. return try RLMRealm.deleteFiles(for: config.rlmConfiguration)
  646. }
  647. // MARK: Internal
  648. internal var rlmRealm: RLMRealm
  649. internal init(_ rlmRealm: RLMRealm) {
  650. self.rlmRealm = rlmRealm
  651. }
  652. }
  653. // MARK: Equatable
  654. extension Realm: Equatable {
  655. /// Returns whether two `Realm` instances are equal.
  656. public static func == (lhs: Realm, rhs: Realm) -> Bool {
  657. return lhs.rlmRealm == rhs.rlmRealm
  658. }
  659. }
  660. // MARK: Notifications
  661. extension Realm {
  662. /// A notification indicating that changes were made to a Realm.
  663. public enum Notification: String {
  664. /**
  665. This notification is posted when the data in a Realm has changed.
  666. `didChange` is posted after a Realm has been refreshed to reflect a write transaction, This can happen when an
  667. autorefresh occurs, `refresh()` is called, after an implicit refresh from `write(_:)`/`beginWrite()`, or after
  668. a local write transaction is committed.
  669. */
  670. case didChange = "RLMRealmDidChangeNotification"
  671. /**
  672. This notification is posted when a write transaction has been committed to a Realm on a different thread for
  673. the same file.
  674. It is not posted if `autorefresh` is enabled, or if the Realm is refreshed before the notification has a chance
  675. to run.
  676. Realms with autorefresh disabled should normally install a handler for this notification which calls
  677. `refresh()` after doing some work. Refreshing the Realm is optional, but not refreshing the Realm may lead to
  678. large Realm files. This is because an extra copy of the data must be kept for the stale Realm.
  679. */
  680. case refreshRequired = "RLMRealmRefreshRequiredNotification"
  681. }
  682. }
  683. /// The type of a block to run for notification purposes when the data in a Realm is modified.
  684. public typealias NotificationBlock = (_ notification: Realm.Notification, _ realm: Realm) -> Void