Realm.swift 44 KB

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