Realm.swift 42 KB

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