Object.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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. `Object` is a class used to define Realm model objects.
  23. In Realm you define your model classes by subclassing `Object` and adding properties to be managed.
  24. You then instantiate and use your custom subclasses instead of using the `Object` class directly.
  25. ```swift
  26. class Dog: Object {
  27. @objc dynamic var name: String = ""
  28. @objc dynamic var adopted: Bool = false
  29. let siblings = List<Dog>()
  30. }
  31. ```
  32. ### Supported property types
  33. - `String`, `NSString`
  34. - `Int`
  35. - `Int8`, `Int16`, `Int32`, `Int64`
  36. - `Float`
  37. - `Double`
  38. - `Bool`
  39. - `Date`, `NSDate`
  40. - `Data`, `NSData`
  41. - `@objc enum` which has been delcared as conforming to `RealmEnum`.
  42. - `RealmOptional<Value>` for optional numeric properties
  43. - `Object` subclasses, to model many-to-one relationships
  44. - `List<Element>`, to model many-to-many relationships
  45. `String`, `NSString`, `Date`, `NSDate`, `Data`, `NSData` and `Object` subclass properties can be declared as optional.
  46. `Int`, `Int8`, `Int16`, `Int32`, `Int64`, `Float`, `Double`, `Bool`, enum, and `List` properties cannot.
  47. To store an optional number, use `RealmOptional<Int>`, `RealmOptional<Float>`, `RealmOptional<Double>`, or
  48. `RealmOptional<Bool>` instead, which wraps an optional numeric value. Lists cannot be optional at all.
  49. All property types except for `List` and `RealmOptional` *must* be declared as `@objc dynamic var`. `List` and
  50. `RealmOptional` properties must be declared as non-dynamic `let` properties. Swift `lazy` properties are not allowed.
  51. Note that none of the restrictions listed above apply to properties that are configured to be ignored by Realm.
  52. ### Querying
  53. You can retrieve all objects of a given type from a Realm by calling the `objects(_:)` instance method.
  54. ### Relationships
  55. See our [Cocoa guide](http://realm.io/docs/cocoa) for more details.
  56. */
  57. @objc(RealmSwiftObject)
  58. open class Object: RLMObjectBase, RealmCollectionValue {
  59. /// :nodoc:
  60. public static func _rlmArray() -> RLMArray<AnyObject> {
  61. return RLMArray(objectClassName: className())
  62. }
  63. // MARK: Initializers
  64. /**
  65. Creates an unmanaged instance of a Realm object.
  66. Call `add(_:)` on a `Realm` instance to add an unmanaged object into that Realm.
  67. - see: `Realm().add(_:)`
  68. */
  69. public override required init() {
  70. super.init()
  71. }
  72. /**
  73. Creates an unmanaged instance of a Realm object.
  74. The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or
  75. dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing one element for each
  76. managed property. An exception will be thrown if any required properties are not present and those properties were
  77. not defined with default values.
  78. When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as
  79. the properties defined in the model.
  80. Call `add(_:)` on a `Realm` instance to add an unmanaged object into that Realm.
  81. - parameter value: The value used to populate the object.
  82. */
  83. public convenience init(value: Any) {
  84. self.init()
  85. RLMInitializeWithValue(self, value, .partialPrivateShared())
  86. }
  87. // MARK: Properties
  88. /// The Realm which manages the object, or `nil` if the object is unmanaged.
  89. public var realm: Realm? {
  90. if let rlmReam = RLMObjectBaseRealm(self) {
  91. return Realm(rlmReam)
  92. }
  93. return nil
  94. }
  95. /// The object schema which lists the managed properties for the object.
  96. public var objectSchema: ObjectSchema {
  97. return ObjectSchema(RLMObjectBaseObjectSchema(self)!)
  98. }
  99. /// Indicates if the object can no longer be accessed because it is now invalid.
  100. ///
  101. /// An object can no longer be accessed if the object has been deleted from the Realm that manages it, or if
  102. /// `invalidate()` is called on that Realm. This property is key-value observable.
  103. @objc dynamic open override var isInvalidated: Bool { return super.isInvalidated }
  104. /// A human-readable description of the object.
  105. open override var description: String { return super.description }
  106. /**
  107. WARNING: This is an internal helper method not intended for public use.
  108. It is not considered part of the public API.
  109. :nodoc:
  110. */
  111. public override final class func _getProperties(withInstance instance: Any) -> [RLMProperty] {
  112. return ObjectUtil.getSwiftProperties(instance as! RLMObjectBase)
  113. }
  114. // MARK: Object Customization
  115. /**
  116. Override this method to specify the name of a property to be used as the primary key.
  117. Only properties of types `String` and `Int` can be designated as the primary key. Primary key properties enforce
  118. uniqueness for each value whenever the property is set, which incurs minor overhead. Indexes are created
  119. automatically for primary key properties.
  120. - returns: The name of the property designated as the primary key, or `nil` if the model has no primary key.
  121. */
  122. @objc open class func primaryKey() -> String? { return nil }
  123. /**
  124. Override this method to specify the names of properties to ignore. These properties will not be managed by
  125. the Realm that manages the object.
  126. - returns: An array of property names to ignore.
  127. */
  128. @objc open class func ignoredProperties() -> [String] { return [] }
  129. /**
  130. Returns an array of property names for properties which should be indexed.
  131. Only string, integer, boolean, `Date`, and `NSDate` properties are supported.
  132. - returns: An array of property names.
  133. */
  134. @objc open class func indexedProperties() -> [String] { return [] }
  135. // MARK: Key-Value Coding & Subscripting
  136. /// Returns or sets the value of the property with the given name.
  137. @objc open subscript(key: String) -> Any? {
  138. get {
  139. if realm == nil {
  140. return value(forKey: key)
  141. }
  142. return dynamicGet(key: key)
  143. }
  144. set(value) {
  145. if realm == nil {
  146. setValue(value, forKey: key)
  147. } else {
  148. RLMDynamicValidatedSet(self, key, value)
  149. }
  150. }
  151. }
  152. private func dynamicGet(key: String) -> Any? {
  153. let objectSchema = RLMObjectBaseObjectSchema(self)!
  154. guard let prop = objectSchema[key] else {
  155. throwRealmException("Invalid property name '\(key) for class \(objectSchema.className)")
  156. }
  157. if let accessor = prop.swiftAccessor {
  158. return accessor.get(Unmanaged.passUnretained(self).toOpaque() + ivar_getOffset(prop.swiftIvar!))
  159. }
  160. if let ivar = prop.swiftIvar, prop.array {
  161. return object_getIvar(self, ivar)
  162. }
  163. return RLMDynamicGet(self, prop)
  164. }
  165. // MARK: Notifications
  166. /**
  167. Registers a block to be called each time the object changes.
  168. The block will be asynchronously called after each write transaction which
  169. deletes the object or modifies any of the managed properties of the object,
  170. including self-assignments that set a property to its existing value.
  171. For write transactions performed on different threads or in different
  172. processes, the block will be called when the managing Realm is
  173. (auto)refreshed to a version including the changes, while for local write
  174. transactions it will be called at some point in the future after the write
  175. transaction is committed.
  176. If no queue is given, notifications are delivered via the standard run
  177. loop, and so can't be delivered while the run loop is blocked by other
  178. activity. If a queue is given, notifications are delivered to that queue
  179. instead. When notifications can't be delivered instantly, multiple
  180. notifications may be coalesced into a single notification.
  181. Unlike with `List` and `Results`, there is no "initial" callback made after
  182. you add a new notification block.
  183. Only objects which are managed by a Realm can be observed in this way. You
  184. must retain the returned token for as long as you want updates to be sent
  185. to the block. To stop receiving updates, call `invalidate()` on the token.
  186. It is safe to capture a strong reference to the observed object within the
  187. callback block. There is no retain cycle due to that the callback is
  188. retained by the returned token and not by the object itself.
  189. - warning: This method cannot be called during a write transaction, or when
  190. the containing Realm is read-only.
  191. - parameter queue: The serial dispatch queue to receive notification on. If
  192. `nil`, notifications are delivered to the current thread.
  193. - parameter block: The block to call with information about changes to the object.
  194. - returns: A token which must be held for as long as you want updates to be delivered.
  195. */
  196. public func observe<T: Object>(on queue: DispatchQueue? = nil,
  197. _ block: @escaping (ObjectChange<T>) -> Void) -> NotificationToken {
  198. precondition(self as? T != nil)
  199. return RLMObjectBaseAddNotificationBlock(self, queue) { object, names, oldValues, newValues, error in
  200. if let error = error {
  201. block(.error(error as NSError))
  202. return
  203. }
  204. guard let names = names, let newValues = newValues else {
  205. block(.deleted)
  206. return
  207. }
  208. block(.change(object as! T, (0..<newValues.count).map { i in
  209. PropertyChange(name: names[i], oldValue: oldValues?[i], newValue: newValues[i])
  210. }))
  211. }
  212. }
  213. // MARK: Dynamic list
  214. /**
  215. Returns a list of `DynamicObject`s for a given property name.
  216. - warning: This method is useful only in specialized circumstances, for example, when building
  217. components that integrate with Realm. If you are simply building an app on Realm, it is
  218. recommended to use instance variables or cast the values returned from key-value coding.
  219. - parameter propertyName: The name of the property.
  220. - returns: A list of `DynamicObject`s.
  221. :nodoc:
  222. */
  223. public func dynamicList(_ propertyName: String) -> List<DynamicObject> {
  224. return noWarnUnsafeBitCast(dynamicGet(key: propertyName) as! RLMListBase,
  225. to: List<DynamicObject>.self)
  226. }
  227. // MARK: Comparison
  228. /**
  229. Returns whether two Realm objects are the same.
  230. Objects are considered the same if and only if they are both managed by the same
  231. Realm and point to the same underlying object in the database.
  232. - note: Equality comparison is implemented by `isEqual(_:)`. If the object type
  233. is defined with a primary key, `isEqual(_:)` behaves identically to this
  234. method. If the object type is not defined with a primary key,
  235. `isEqual(_:)` uses the `NSObject` behavior of comparing object identity.
  236. This method can be used to compare two objects for database equality
  237. whether or not their object type defines a primary key.
  238. - parameter object: The object to compare the receiver to.
  239. */
  240. public func isSameObject(as object: Object?) -> Bool {
  241. return RLMObjectBaseAreEqual(self, object)
  242. }
  243. }
  244. extension Object: ThreadConfined {
  245. /**
  246. Indicates if this object is frozen.
  247. - see: `Object.freeze()`
  248. */
  249. public var isFrozen: Bool { return realm?.isFrozen ?? false }
  250. /**
  251. Returns a frozen (immutable) snapshot of this object.
  252. The frozen copy is an immutable object which contains the same data as this
  253. object currently contains, but will not update when writes are made to the
  254. containing Realm. Unlike live objects, frozen objects can be accessed from any
  255. thread.
  256. - warning: Holding onto a frozen object for an extended period while performing write
  257. transaction on the Realm may result in the Realm file growing to large sizes. See
  258. `Realm.Configuration.maximumNumberOfActiveVersions` for more information.
  259. - warning: This method can only be called on a managed object.
  260. */
  261. public func freeze() -> Self {
  262. return realm!.freeze(self)
  263. }
  264. }
  265. /**
  266. Information about a specific property which changed in an `Object` change notification.
  267. */
  268. public struct PropertyChange {
  269. /**
  270. The name of the property which changed.
  271. */
  272. public let name: String
  273. /**
  274. Value of the property before the change occurred. This is not supplied if
  275. the change happened on the same thread as the notification and for `List`
  276. properties.
  277. For object properties this will give the object which was previously
  278. linked to, but that object will have its new values and not the values it
  279. had before the changes. This means that `previousValue` may be a deleted
  280. object, and you will need to check `isInvalidated` before accessing any
  281. of its properties.
  282. */
  283. public let oldValue: Any?
  284. /**
  285. The value of the property after the change occurred. This is not supplied
  286. for `List` properties and will always be nil.
  287. */
  288. public let newValue: Any?
  289. }
  290. /**
  291. Information about the changes made to an object which is passed to `Object`'s
  292. notification blocks.
  293. */
  294. public enum ObjectChange<T: Object> {
  295. /**
  296. If an error occurs, notification blocks are called one time with a `.error`
  297. result and an `NSError` containing details about the error. Currently the
  298. only errors which can occur are when opening the Realm on a background
  299. worker thread to calculate the change set. The callback will never be
  300. called again after `.error` is delivered.
  301. */
  302. case error(_ error: NSError)
  303. /**
  304. One or more of the properties of the object have been changed.
  305. */
  306. case change(_: T, _: [PropertyChange])
  307. /// The object has been deleted from the Realm.
  308. case deleted
  309. }
  310. /// Object interface which allows untyped getters and setters for Objects.
  311. /// :nodoc:
  312. public final class DynamicObject: Object {
  313. public override subscript(key: String) -> Any? {
  314. get {
  315. let value = RLMDynamicGetByName(self, key)
  316. if let array = value as? RLMArray<AnyObject> {
  317. return List<DynamicObject>(objc: array)
  318. }
  319. return value
  320. }
  321. set(value) {
  322. RLMDynamicValidatedSet(self, key, value)
  323. }
  324. }
  325. /// :nodoc:
  326. public override func dynamicList(_ propertyName: String) -> List<DynamicObject> {
  327. return self[propertyName] as! List<DynamicObject>
  328. }
  329. /// :nodoc:
  330. public override func value(forUndefinedKey key: String) -> Any? {
  331. return self[key]
  332. }
  333. /// :nodoc:
  334. public override func setValue(_ value: Any?, forUndefinedKey key: String) {
  335. self[key] = value
  336. }
  337. /// :nodoc:
  338. public override class func shouldIncludeInDefaultSchema() -> Bool {
  339. return false
  340. }
  341. }
  342. /**
  343. An enum type which can be stored on a Realm Object.
  344. Only `@objc` enums backed by an Int can be stored on a Realm object, and the
  345. enum type must explicitly conform to this protocol. For example:
  346. ```
  347. @objc enum class MyEnum: Int, RealmEnum {
  348. case first = 1
  349. case second = 2
  350. case third = 7
  351. }
  352. class MyModel: Object {
  353. @objc dynamic enumProperty = MyEnum.first
  354. let optionalEnumProperty = RealmOptional<MyEnum>()
  355. }
  356. ```
  357. */
  358. public protocol RealmEnum: RealmOptionalType, _ManagedPropertyType {
  359. /// :nodoc:
  360. // swiftlint:disable:next identifier_name
  361. static func _rlmToRawValue(_ value: Any) -> Any
  362. /// :nodoc:
  363. // swiftlint:disable:next identifier_name
  364. static func _rlmFromRawValue(_ value: Any) -> Any
  365. }
  366. // MARK: - Implementation
  367. /// :nodoc:
  368. public extension RealmEnum where Self: RawRepresentable, Self.RawValue: _ManagedPropertyType {
  369. // swiftlint:disable:next identifier_name
  370. static func _rlmToRawValue(_ value: Any) -> Any {
  371. return (value as! Self).rawValue
  372. }
  373. // swiftlint:disable:next identifier_name
  374. static func _rlmFromRawValue(_ value: Any) -> Any {
  375. return Self.init(rawValue: value as! RawValue)!
  376. }
  377. // swiftlint:disable:next identifier_name
  378. static func _rlmProperty(_ prop: RLMProperty) {
  379. RawValue._rlmProperty(prop)
  380. }
  381. }
  382. // A type which can be a managed property on a Realm object
  383. /// :nodoc:
  384. public protocol _ManagedPropertyType {
  385. // swiftlint:disable:next identifier_name
  386. func _rlmProperty(_ prop: RLMProperty)
  387. // swiftlint:disable:next identifier_name
  388. static func _rlmProperty(_ prop: RLMProperty)
  389. // swiftlint:disable:next identifier_name
  390. static func _rlmRequireObjc() -> Bool
  391. }
  392. /// :nodoc:
  393. extension _ManagedPropertyType {
  394. // swiftlint:disable:next identifier_name
  395. public func _rlmProperty(_ prop: RLMProperty) { }
  396. // swiftlint:disable:next identifier_name
  397. public static func _rlmRequireObjc() -> Bool { return true }
  398. }
  399. /// :nodoc:
  400. extension Int: _ManagedPropertyType {
  401. // swiftlint:disable:next identifier_name
  402. public static func _rlmProperty(_ prop: RLMProperty) {
  403. prop.type = .int
  404. }
  405. }
  406. /// :nodoc:
  407. extension Int8: _ManagedPropertyType {
  408. // swiftlint:disable:next identifier_name
  409. public static func _rlmProperty(_ prop: RLMProperty) {
  410. prop.type = .int
  411. }
  412. }
  413. /// :nodoc:
  414. extension Int16: _ManagedPropertyType {
  415. // swiftlint:disable:next identifier_name
  416. public static func _rlmProperty(_ prop: RLMProperty) {
  417. prop.type = .int
  418. }
  419. }
  420. /// :nodoc:
  421. extension Int32: _ManagedPropertyType {
  422. // swiftlint:disable:next identifier_name
  423. public static func _rlmProperty(_ prop: RLMProperty) {
  424. prop.type = .int
  425. }
  426. }
  427. /// :nodoc:
  428. extension Int64: _ManagedPropertyType {
  429. // swiftlint:disable:next identifier_name
  430. public static func _rlmProperty(_ prop: RLMProperty) {
  431. prop.type = .int
  432. }
  433. }
  434. /// :nodoc:
  435. extension Float: _ManagedPropertyType {
  436. // swiftlint:disable:next identifier_name
  437. public static func _rlmProperty(_ prop: RLMProperty) {
  438. prop.type = .float
  439. }
  440. }
  441. /// :nodoc:
  442. extension Double: _ManagedPropertyType {
  443. // swiftlint:disable:next identifier_name
  444. public static func _rlmProperty(_ prop: RLMProperty) {
  445. prop.type = .double
  446. }
  447. }
  448. /// :nodoc:
  449. extension Bool: _ManagedPropertyType {
  450. // swiftlint:disable:next identifier_name
  451. public static func _rlmProperty(_ prop: RLMProperty) {
  452. prop.type = .bool
  453. }
  454. }
  455. /// :nodoc:
  456. extension String: _ManagedPropertyType {
  457. // swiftlint:disable:next identifier_name
  458. public static func _rlmProperty(_ prop: RLMProperty) {
  459. prop.type = .string
  460. }
  461. }
  462. /// :nodoc:
  463. extension NSString: _ManagedPropertyType {
  464. // swiftlint:disable:next identifier_name
  465. public static func _rlmProperty(_ prop: RLMProperty) {
  466. prop.type = .string
  467. }
  468. }
  469. /// :nodoc:
  470. extension Data: _ManagedPropertyType {
  471. // swiftlint:disable:next identifier_name
  472. public static func _rlmProperty(_ prop: RLMProperty) {
  473. prop.type = .data
  474. }
  475. }
  476. /// :nodoc:
  477. extension NSData: _ManagedPropertyType {
  478. // swiftlint:disable:next identifier_name
  479. public static func _rlmProperty(_ prop: RLMProperty) {
  480. prop.type = .data
  481. }
  482. }
  483. /// :nodoc:
  484. extension Date: _ManagedPropertyType {
  485. // swiftlint:disable:next identifier_name
  486. public static func _rlmProperty(_ prop: RLMProperty) {
  487. prop.type = .date
  488. }
  489. }
  490. /// :nodoc:
  491. extension NSDate: _ManagedPropertyType {
  492. // swiftlint:disable:next identifier_name
  493. public static func _rlmProperty(_ prop: RLMProperty) {
  494. prop.type = .date
  495. }
  496. }
  497. /// :nodoc:
  498. extension Object: _ManagedPropertyType {
  499. // swiftlint:disable:next identifier_name
  500. public static func _rlmProperty(_ prop: RLMProperty) {
  501. if !prop.optional && !prop.array {
  502. throwRealmException("Object property '\(prop.name)' must be marked as optional.")
  503. }
  504. if prop.optional && prop.array {
  505. throwRealmException("List<\(className())> property '\(prop.name)' must not be marked as optional.")
  506. }
  507. prop.type = .object
  508. prop.objectClassName = className()
  509. }
  510. }
  511. /// :nodoc:
  512. extension List: _ManagedPropertyType where Element: _ManagedPropertyType {
  513. // swiftlint:disable:next identifier_name
  514. public static func _rlmProperty(_ prop: RLMProperty) {
  515. prop.array = true
  516. Element._rlmProperty(prop)
  517. }
  518. // swiftlint:disable:next identifier_name
  519. public static func _rlmRequireObjc() -> Bool { return false }
  520. }
  521. /// :nodoc:
  522. class LinkingObjectsAccessor<Element: Object>: RLMManagedPropertyAccessor {
  523. @objc override class func initializeObject(_ ptr: UnsafeMutableRawPointer,
  524. parent: RLMObjectBase, property: RLMProperty) {
  525. ptr.assumingMemoryBound(to: LinkingObjects.self).pointee.handle = RLMLinkingObjectsHandle(object: parent, property: property)
  526. }
  527. @objc override class func get(_ ptr: UnsafeMutableRawPointer) -> Any {
  528. return ptr.assumingMemoryBound(to: LinkingObjects<Element>.self).pointee
  529. }
  530. }
  531. /// :nodoc:
  532. extension LinkingObjects: _ManagedPropertyType {
  533. // swiftlint:disable:next identifier_name
  534. public static func _rlmProperty(_ prop: RLMProperty) {
  535. prop.array = true
  536. prop.type = .linkingObjects
  537. prop.objectClassName = Element.className()
  538. prop.swiftAccessor = LinkingObjectsAccessor<Element>.self
  539. }
  540. // swiftlint:disable:next identifier_name
  541. public func _rlmProperty(_ prop: RLMProperty) {
  542. prop.linkOriginPropertyName = self.propertyName
  543. }
  544. // swiftlint:disable:next identifier_name
  545. public static func _rlmRequireObjc() -> Bool { return false }
  546. }
  547. /// :nodoc:
  548. extension Optional: _ManagedPropertyType where Wrapped: _ManagedPropertyType {
  549. // swiftlint:disable:next identifier_name
  550. public static func _rlmProperty(_ prop: RLMProperty) {
  551. prop.optional = true
  552. Wrapped._rlmProperty(prop)
  553. }
  554. }
  555. /// :nodoc:
  556. extension RealmOptional: _ManagedPropertyType where Value: _ManagedPropertyType {
  557. // swiftlint:disable:next identifier_name
  558. public static func _rlmProperty(_ prop: RLMProperty) {
  559. prop.optional = true
  560. Value._rlmProperty(prop)
  561. }
  562. // swiftlint:disable:next identifier_name
  563. public static func _rlmRequireObjc() -> Bool { return false }
  564. }
  565. /// :nodoc:
  566. internal class ObjectUtil {
  567. private static let runOnce: Void = {
  568. RLMSwiftAsFastEnumeration = { (obj: Any) -> Any? in
  569. // Intermediate cast to AnyObject due to https://bugs.swift.org/browse/SR-8651
  570. if let collection = obj as AnyObject as? _RealmCollectionEnumerator {
  571. return collection._asNSFastEnumerator()
  572. }
  573. return nil
  574. }
  575. }()
  576. private class func swiftVersion() -> NSString {
  577. #if SWIFT_PACKAGE
  578. return "5.1"
  579. #else
  580. return swiftLanguageVersion as NSString
  581. #endif
  582. }
  583. // If the property is a storage property for a lazy Swift property, return
  584. // the base property name (e.g. `foo.storage` becomes `foo`). Otherwise, nil.
  585. private static func baseName(forLazySwiftProperty name: String) -> String? {
  586. // A Swift lazy var shows up as two separate children on the reflection tree:
  587. // one named 'x', and another that is optional and is named 'x.storage'. Note
  588. // that '.' is illegal in either a Swift or Objective-C property name.
  589. if let storageRange = name.range(of: ".storage", options: [.anchored, .backwards]) {
  590. return String(name[..<storageRange.lowerBound])
  591. }
  592. // Xcode 11 changed the name of the storage property to "$__lazy_storage_$_propName"
  593. if let storageRange = name.range(of: "$__lazy_storage_$_", options: [.anchored]) {
  594. return String(name[storageRange.upperBound...])
  595. }
  596. return nil
  597. }
  598. // Reflect an object, returning only children representing managed Realm properties.
  599. private static func getNonIgnoredMirrorChildren(for object: Any) -> [Mirror.Child] {
  600. let ignoredPropNames: Set<String>
  601. if let realmObject = object as? Object {
  602. ignoredPropNames = Set(type(of: realmObject).ignoredProperties())
  603. } else {
  604. ignoredPropNames = Set()
  605. }
  606. return Mirror(reflecting: object).children.filter { (prop: Mirror.Child) -> Bool in
  607. guard let label = prop.label else {
  608. return false
  609. }
  610. if ignoredPropNames.contains(label) {
  611. return false
  612. }
  613. if let lazyBaseName = baseName(forLazySwiftProperty: label) {
  614. if ignoredPropNames.contains(lazyBaseName) {
  615. return false
  616. }
  617. // Managed lazy property; not currently supported.
  618. // FIXME: revisit this once Swift gets property behaviors/property macros.
  619. throwRealmException("Lazy managed property '\(lazyBaseName)' is not allowed on a Realm Swift object"
  620. + " class. Either add the property to the ignored properties list or make it non-lazy.")
  621. }
  622. return true
  623. }
  624. }
  625. internal class func getSwiftProperties(_ object: RLMObjectBase) -> [RLMProperty] {
  626. _ = ObjectUtil.runOnce
  627. let cls = type(of: object)
  628. var indexedProperties: Set<String>!
  629. let columnNames = cls._realmColumnNames()
  630. if let realmObject = object as? Object {
  631. indexedProperties = Set(type(of: realmObject).indexedProperties())
  632. } else {
  633. indexedProperties = Set()
  634. }
  635. return getNonIgnoredMirrorChildren(for: object).compactMap { prop in
  636. guard let label = prop.label else { return nil }
  637. var rawValue = prop.value
  638. if let value = rawValue as? RealmEnum {
  639. rawValue = type(of: value)._rlmToRawValue(value)
  640. }
  641. guard let value = rawValue as? _ManagedPropertyType else {
  642. if class_getProperty(cls, label) != nil {
  643. throwRealmException("Property \(cls).\(label) is declared as \(type(of: prop.value)), which is not a supported managed Object property type. If it is not supposed to be a managed property, either add it to `ignoredProperties()` or do not declare it as `@objc dynamic`. See https://realm.io/docs/swift/latest/api/Classes/Object.html for more information.")
  644. }
  645. if prop.value as? RealmOptionalProtocol != nil {
  646. throwRealmException("Property \(cls).\(label) has unsupported RealmOptional type \(type(of: prop.value)). Extending RealmOptionalType with custom types is not currently supported. ")
  647. }
  648. return nil
  649. }
  650. RLMValidateSwiftPropertyName(label)
  651. let valueType = type(of: value)
  652. let property = RLMProperty()
  653. property.name = label
  654. property.indexed = indexedProperties.contains(label)
  655. property.columnName = columnNames?[label]
  656. valueType._rlmProperty(property)
  657. value._rlmProperty(property)
  658. if let objcProp = class_getProperty(cls, label) {
  659. var count: UInt32 = 0
  660. let attrs = property_copyAttributeList(objcProp, &count)!
  661. defer {
  662. free(attrs)
  663. }
  664. var computed = true
  665. for i in 0..<Int(count) {
  666. let attr = attrs[i]
  667. switch attr.name[0] {
  668. case Int8(UInt8(ascii: "R")): // Read only
  669. return nil
  670. case Int8(UInt8(ascii: "V")): // Ivar name
  671. computed = false
  672. case Int8(UInt8(ascii: "G")): // Getter name
  673. property.getterName = String(cString: attr.value)
  674. case Int8(UInt8(ascii: "S")): // Setter name
  675. property.setterName = String(cString: attr.value)
  676. default:
  677. break
  678. }
  679. }
  680. // If there's no ivar name and no ivar with the same name as
  681. // the property then this is a computed property and we should
  682. // implicitly ignore it
  683. if computed && class_getInstanceVariable(cls, label) == nil {
  684. return nil
  685. }
  686. } else if valueType._rlmRequireObjc() {
  687. // Implicitly ignore non-@objc dynamic properties
  688. return nil
  689. } else {
  690. property.swiftIvar = class_getInstanceVariable(cls, label)
  691. }
  692. property.updateAccessors()
  693. return property
  694. }
  695. }
  696. }
  697. // MARK: AssistedObjectiveCBridgeable
  698. // FIXME: Remove when `as! Self` can be written
  699. private func forceCastToInferred<T, V>(_ x: T) -> V {
  700. return x as! V
  701. }
  702. extension Object: AssistedObjectiveCBridgeable {
  703. internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self {
  704. return forceCastToInferred(objectiveCValue)
  705. }
  706. internal var bridged: (objectiveCValue: Any, metadata: Any?) {
  707. return (objectiveCValue: unsafeCastToRLMObject(), metadata: nil)
  708. }
  709. }