Realm.swift 42 KB

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