Object.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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, ThreadConfined, 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.
  103. public override final 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. Notifications are delivered via the standard run loop, and so can't be
  177. delivered while the run loop is blocked by other activity. When
  178. notifications can't be delivered instantly, multiple notifications may be
  179. coalesced into a single notification.
  180. Unlike with `List` and `Results`, there is no "initial" callback made after
  181. you add a new notification block.
  182. Only objects which are managed by a Realm can be observed in this way. You
  183. must retain the returned token for as long as you want updates to be sent
  184. to the block. To stop receiving updates, call `invalidate()` on the token.
  185. It is safe to capture a strong reference to the observed object within the
  186. callback block. There is no retain cycle due to that the callback is
  187. retained by the returned token and not by the object itself.
  188. - warning: This method cannot be called during a write transaction, or when
  189. the containing Realm is read-only.
  190. - parameter block: The block to call with information about changes to the object.
  191. - returns: A token which must be held for as long as you want updates to be delivered.
  192. */
  193. public func observe(_ block: @escaping (ObjectChange) -> Void) -> NotificationToken {
  194. return RLMObjectAddNotificationBlock(self, { names, oldValues, newValues, error in
  195. if let error = error {
  196. block(.error(error as NSError))
  197. return
  198. }
  199. guard let names = names, let newValues = newValues else {
  200. block(.deleted)
  201. return
  202. }
  203. block(.change((0..<newValues.count).map { i in
  204. PropertyChange(name: names[i], oldValue: oldValues?[i], newValue: newValues[i])
  205. }))
  206. })
  207. }
  208. // MARK: Dynamic list
  209. /**
  210. Returns a list of `DynamicObject`s for a given property name.
  211. - warning: This method is useful only in specialized circumstances, for example, when building
  212. components that integrate with Realm. If you are simply building an app on Realm, it is
  213. recommended to use instance variables or cast the values returned from key-value coding.
  214. - parameter propertyName: The name of the property.
  215. - returns: A list of `DynamicObject`s.
  216. :nodoc:
  217. */
  218. public func dynamicList(_ propertyName: String) -> List<DynamicObject> {
  219. return noWarnUnsafeBitCast(dynamicGet(key: propertyName) as! RLMListBase,
  220. to: List<DynamicObject>.self)
  221. }
  222. // MARK: Comparison
  223. /**
  224. Returns whether two Realm objects are the same.
  225. Objects are considered the same if and only if they are both managed by the same
  226. Realm and point to the same underlying object in the database.
  227. - note: Equality comparison is implemented by `isEqual(_:)`. If the object type
  228. is defined with a primary key, `isEqual(_:)` behaves identically to this
  229. method. If the object type is not defined with a primary key,
  230. `isEqual(_:)` uses the `NSObject` behavior of comparing object identity.
  231. This method can be used to compare two objects for database equality
  232. whether or not their object type defines a primary key.
  233. - parameter object: The object to compare the receiver to.
  234. */
  235. public func isSameObject(as object: Object?) -> Bool {
  236. return RLMObjectBaseAreEqual(self, object)
  237. }
  238. }
  239. /**
  240. Information about a specific property which changed in an `Object` change notification.
  241. */
  242. public struct PropertyChange {
  243. /**
  244. The name of the property which changed.
  245. */
  246. public let name: String
  247. /**
  248. Value of the property before the change occurred. This is not supplied if
  249. the change happened on the same thread as the notification and for `List`
  250. properties.
  251. For object properties this will give the object which was previously
  252. linked to, but that object will have its new values and not the values it
  253. had before the changes. This means that `previousValue` may be a deleted
  254. object, and you will need to check `isInvalidated` before accessing any
  255. of its properties.
  256. */
  257. public let oldValue: Any?
  258. /**
  259. The value of the property after the change occurred. This is not supplied
  260. for `List` properties and will always be nil.
  261. */
  262. public let newValue: Any?
  263. }
  264. /**
  265. Information about the changes made to an object which is passed to `Object`'s
  266. notification blocks.
  267. */
  268. public enum ObjectChange {
  269. /**
  270. If an error occurs, notification blocks are called one time with a `.error`
  271. result and an `NSError` containing details about the error. Currently the
  272. only errors which can occur are when opening the Realm on a background
  273. worker thread to calculate the change set. The callback will never be
  274. called again after `.error` is delivered.
  275. */
  276. case error(_: NSError)
  277. /**
  278. One or more of the properties of the object have been changed.
  279. */
  280. case change(_: [PropertyChange])
  281. /// The object has been deleted from the Realm.
  282. case deleted
  283. }
  284. /// Object interface which allows untyped getters and setters for Objects.
  285. /// :nodoc:
  286. public final class DynamicObject: Object {
  287. public override subscript(key: String) -> Any? {
  288. get {
  289. let value = RLMDynamicGetByName(self, key)
  290. if let array = value as? RLMArray<AnyObject> {
  291. return List<DynamicObject>(rlmArray: array)
  292. }
  293. return value
  294. }
  295. set(value) {
  296. RLMDynamicValidatedSet(self, key, value)
  297. }
  298. }
  299. /// :nodoc:
  300. public override func dynamicList(_ propertyName: String) -> List<DynamicObject> {
  301. return self[propertyName] as! List<DynamicObject>
  302. }
  303. /// :nodoc:
  304. public override func value(forUndefinedKey key: String) -> Any? {
  305. return self[key]
  306. }
  307. /// :nodoc:
  308. public override func setValue(_ value: Any?, forUndefinedKey key: String) {
  309. self[key] = value
  310. }
  311. /// :nodoc:
  312. public override class func shouldIncludeInDefaultSchema() -> Bool {
  313. return false
  314. }
  315. }
  316. /**
  317. An enum type which can be stored on a Realm Object.
  318. Only `@objc` enums backed by an Int can be stored on a Realm object, and the
  319. enum type must explicitly conform to this protocol. For example:
  320. ```
  321. @objc enum class MyEnum: Int, RealmEnum {
  322. case first = 1
  323. case second = 2
  324. case third = 7
  325. }
  326. class MyModel: Object {
  327. @objc dynamic enumProperty = MyEnum.first
  328. let optionalEnumProperty = RealmOptional<MyEnum>()
  329. }
  330. ```
  331. */
  332. public protocol RealmEnum: RealmOptionalType, _ManagedPropertyType {
  333. /// :nodoc:
  334. // swiftlint:disable:next identifier_name
  335. static func _rlmToRawValue(_ value: Any) -> Any
  336. /// :nodoc:
  337. // swiftlint:disable:next identifier_name
  338. static func _rlmFromRawValue(_ value: Any) -> Any
  339. }
  340. // MARK: - Implementation
  341. /// :nodoc:
  342. public extension RealmEnum where Self: RawRepresentable, Self.RawValue: _ManagedPropertyType {
  343. // swiftlint:disable:next identifier_name
  344. static func _rlmToRawValue(_ value: Any) -> Any {
  345. return (value as! Self).rawValue
  346. }
  347. // swiftlint:disable:next identifier_name
  348. static func _rlmFromRawValue(_ value: Any) -> Any {
  349. return Self.init(rawValue: value as! RawValue)!
  350. }
  351. // swiftlint:disable:next identifier_name
  352. static func _rlmProperty(_ prop: RLMProperty) {
  353. RawValue._rlmProperty(prop)
  354. }
  355. }
  356. // A type which can be a managed property on a Realm object
  357. /// :nodoc:
  358. public protocol _ManagedPropertyType {
  359. // swiftlint:disable:next identifier_name
  360. func _rlmProperty(_ prop: RLMProperty)
  361. // swiftlint:disable:next identifier_name
  362. static func _rlmProperty(_ prop: RLMProperty)
  363. // swiftlint:disable:next identifier_name
  364. static func _rlmRequireObjc() -> Bool
  365. }
  366. /// :nodoc:
  367. extension _ManagedPropertyType {
  368. // swiftlint:disable:next identifier_name
  369. public func _rlmProperty(_ prop: RLMProperty) { }
  370. // swiftlint:disable:next identifier_name
  371. public static func _rlmRequireObjc() -> Bool { return true }
  372. }
  373. /// :nodoc:
  374. extension Int: _ManagedPropertyType {
  375. // swiftlint:disable:next identifier_name
  376. public static func _rlmProperty(_ prop: RLMProperty) {
  377. prop.type = .int
  378. }
  379. }
  380. /// :nodoc:
  381. extension Int8: _ManagedPropertyType {
  382. // swiftlint:disable:next identifier_name
  383. public static func _rlmProperty(_ prop: RLMProperty) {
  384. prop.type = .int
  385. }
  386. }
  387. /// :nodoc:
  388. extension Int16: _ManagedPropertyType {
  389. // swiftlint:disable:next identifier_name
  390. public static func _rlmProperty(_ prop: RLMProperty) {
  391. prop.type = .int
  392. }
  393. }
  394. /// :nodoc:
  395. extension Int32: _ManagedPropertyType {
  396. // swiftlint:disable:next identifier_name
  397. public static func _rlmProperty(_ prop: RLMProperty) {
  398. prop.type = .int
  399. }
  400. }
  401. /// :nodoc:
  402. extension Int64: _ManagedPropertyType {
  403. // swiftlint:disable:next identifier_name
  404. public static func _rlmProperty(_ prop: RLMProperty) {
  405. prop.type = .int
  406. }
  407. }
  408. /// :nodoc:
  409. extension Float: _ManagedPropertyType {
  410. // swiftlint:disable:next identifier_name
  411. public static func _rlmProperty(_ prop: RLMProperty) {
  412. prop.type = .float
  413. }
  414. }
  415. /// :nodoc:
  416. extension Double: _ManagedPropertyType {
  417. // swiftlint:disable:next identifier_name
  418. public static func _rlmProperty(_ prop: RLMProperty) {
  419. prop.type = .double
  420. }
  421. }
  422. /// :nodoc:
  423. extension Bool: _ManagedPropertyType {
  424. // swiftlint:disable:next identifier_name
  425. public static func _rlmProperty(_ prop: RLMProperty) {
  426. prop.type = .bool
  427. }
  428. }
  429. /// :nodoc:
  430. extension String: _ManagedPropertyType {
  431. // swiftlint:disable:next identifier_name
  432. public static func _rlmProperty(_ prop: RLMProperty) {
  433. prop.type = .string
  434. }
  435. }
  436. /// :nodoc:
  437. extension NSString: _ManagedPropertyType {
  438. // swiftlint:disable:next identifier_name
  439. public static func _rlmProperty(_ prop: RLMProperty) {
  440. prop.type = .string
  441. }
  442. }
  443. /// :nodoc:
  444. extension Data: _ManagedPropertyType {
  445. // swiftlint:disable:next identifier_name
  446. public static func _rlmProperty(_ prop: RLMProperty) {
  447. prop.type = .data
  448. }
  449. }
  450. /// :nodoc:
  451. extension NSData: _ManagedPropertyType {
  452. // swiftlint:disable:next identifier_name
  453. public static func _rlmProperty(_ prop: RLMProperty) {
  454. prop.type = .data
  455. }
  456. }
  457. /// :nodoc:
  458. extension Date: _ManagedPropertyType {
  459. // swiftlint:disable:next identifier_name
  460. public static func _rlmProperty(_ prop: RLMProperty) {
  461. prop.type = .date
  462. }
  463. }
  464. /// :nodoc:
  465. extension NSDate: _ManagedPropertyType {
  466. // swiftlint:disable:next identifier_name
  467. public static func _rlmProperty(_ prop: RLMProperty) {
  468. prop.type = .date
  469. }
  470. }
  471. /// :nodoc:
  472. extension Object: _ManagedPropertyType {
  473. // swiftlint:disable:next identifier_name
  474. public static func _rlmProperty(_ prop: RLMProperty) {
  475. if !prop.optional && !prop.array {
  476. throwRealmException("Object property '\(prop.name)' must be marked as optional.")
  477. }
  478. if prop.optional && prop.array {
  479. throwRealmException("List<\(className())> property '\(prop.name)' must not be marked as optional.")
  480. }
  481. prop.type = .object
  482. prop.objectClassName = className()
  483. }
  484. }
  485. /// :nodoc:
  486. extension List: _ManagedPropertyType where Element: _ManagedPropertyType {
  487. // swiftlint:disable:next identifier_name
  488. public static func _rlmProperty(_ prop: RLMProperty) {
  489. prop.array = true
  490. Element._rlmProperty(prop)
  491. }
  492. // swiftlint:disable:next identifier_name
  493. public static func _rlmRequireObjc() -> Bool { return false }
  494. }
  495. /// :nodoc:
  496. class LinkingObjectsAccessor<Element: Object>: RLMManagedPropertyAccessor {
  497. @objc override class func initializeObject(_ ptr: UnsafeMutableRawPointer,
  498. parent: RLMObjectBase, property: RLMProperty) {
  499. ptr.assumingMemoryBound(to: LinkingObjects.self).pointee.handle = RLMLinkingObjectsHandle(object: parent, property: property)
  500. }
  501. @objc override class func get(_ ptr: UnsafeMutableRawPointer) -> Any {
  502. return ptr.assumingMemoryBound(to: LinkingObjects<Element>.self).pointee
  503. }
  504. }
  505. /// :nodoc:
  506. extension LinkingObjects: _ManagedPropertyType {
  507. // swiftlint:disable:next identifier_name
  508. public static func _rlmProperty(_ prop: RLMProperty) {
  509. prop.array = true
  510. prop.type = .linkingObjects
  511. prop.objectClassName = Element.className()
  512. prop.swiftAccessor = LinkingObjectsAccessor<Element>.self
  513. }
  514. // swiftlint:disable:next identifier_name
  515. public func _rlmProperty(_ prop: RLMProperty) {
  516. prop.linkOriginPropertyName = self.propertyName
  517. }
  518. // swiftlint:disable:next identifier_name
  519. public static func _rlmRequireObjc() -> Bool { return false }
  520. }
  521. /// :nodoc:
  522. extension Optional: _ManagedPropertyType where Wrapped: _ManagedPropertyType {
  523. // swiftlint:disable:next identifier_name
  524. public static func _rlmProperty(_ prop: RLMProperty) {
  525. prop.optional = true
  526. Wrapped._rlmProperty(prop)
  527. }
  528. }
  529. /// :nodoc:
  530. extension RealmOptional: _ManagedPropertyType where Value: _ManagedPropertyType {
  531. // swiftlint:disable:next identifier_name
  532. public static func _rlmProperty(_ prop: RLMProperty) {
  533. prop.optional = true
  534. Value._rlmProperty(prop)
  535. }
  536. // swiftlint:disable:next identifier_name
  537. public static func _rlmRequireObjc() -> Bool { return false }
  538. }
  539. /// :nodoc:
  540. internal class ObjectUtil {
  541. private static let runOnce: Void = {
  542. RLMSwiftAsFastEnumeration = { (obj: Any) -> Any? in
  543. // Intermediate cast to AnyObject due to https://bugs.swift.org/browse/SR-8651
  544. if let collection = obj as AnyObject as? _RealmCollectionEnumerator {
  545. return collection._asNSFastEnumerator()
  546. }
  547. return nil
  548. }
  549. }()
  550. private class func swiftVersion() -> NSString {
  551. #if SWIFT_PACKAGE
  552. return "5.1"
  553. #else
  554. return swiftLanguageVersion as NSString
  555. #endif
  556. }
  557. // If the property is a storage property for a lazy Swift property, return
  558. // the base property name (e.g. `foo.storage` becomes `foo`). Otherwise, nil.
  559. private static func baseName(forLazySwiftProperty name: String) -> String? {
  560. // A Swift lazy var shows up as two separate children on the reflection tree:
  561. // one named 'x', and another that is optional and is named 'x.storage'. Note
  562. // that '.' is illegal in either a Swift or Objective-C property name.
  563. if let storageRange = name.range(of: ".storage", options: [.anchored, .backwards]) {
  564. return String(name[..<storageRange.lowerBound])
  565. }
  566. // Xcode 11 changed the name of the storage property to "$__lazy_storage_$_propName"
  567. if let storageRange = name.range(of: "$__lazy_storage_$_", options: [.anchored]) {
  568. return String(name[storageRange.upperBound...])
  569. }
  570. return nil
  571. }
  572. // Reflect an object, returning only children representing managed Realm properties.
  573. private static func getNonIgnoredMirrorChildren(for object: Any) -> [Mirror.Child] {
  574. let ignoredPropNames: Set<String>
  575. if let realmObject = object as? Object {
  576. ignoredPropNames = Set(type(of: realmObject).ignoredProperties())
  577. } else {
  578. ignoredPropNames = Set()
  579. }
  580. return Mirror(reflecting: object).children.filter { (prop: Mirror.Child) -> Bool in
  581. guard let label = prop.label else {
  582. return false
  583. }
  584. if ignoredPropNames.contains(label) {
  585. return false
  586. }
  587. if let lazyBaseName = baseName(forLazySwiftProperty: label) {
  588. if ignoredPropNames.contains(lazyBaseName) {
  589. return false
  590. }
  591. // Managed lazy property; not currently supported.
  592. // FIXME: revisit this once Swift gets property behaviors/property macros.
  593. throwRealmException("Lazy managed property '\(lazyBaseName)' is not allowed on a Realm Swift object"
  594. + " class. Either add the property to the ignored properties list or make it non-lazy.")
  595. }
  596. return true
  597. }
  598. }
  599. internal class func getSwiftProperties(_ object: RLMObjectBase) -> [RLMProperty] {
  600. _ = ObjectUtil.runOnce
  601. let cls = type(of: object)
  602. var indexedProperties: Set<String>!
  603. let columnNames = cls._realmColumnNames()
  604. if let realmObject = object as? Object {
  605. indexedProperties = Set(type(of: realmObject).indexedProperties())
  606. } else {
  607. indexedProperties = Set()
  608. }
  609. return getNonIgnoredMirrorChildren(for: object).compactMap { prop in
  610. guard let label = prop.label else { return nil }
  611. var rawValue = prop.value
  612. if let value = rawValue as? RealmEnum {
  613. rawValue = type(of: value)._rlmToRawValue(value)
  614. }
  615. guard let value = rawValue as? _ManagedPropertyType else {
  616. if class_getProperty(cls, label) != nil {
  617. 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.")
  618. }
  619. if prop.value as? RealmOptionalProtocol != nil {
  620. throwRealmException("Property \(cls).\(label) has unsupported RealmOptional type \(type(of: prop.value)). Extending RealmOptionalType with custom types is not currently supported. ")
  621. }
  622. return nil
  623. }
  624. RLMValidateSwiftPropertyName(label)
  625. let valueType = type(of: value)
  626. let property = RLMProperty()
  627. property.name = label
  628. property.indexed = indexedProperties.contains(label)
  629. property.columnName = columnNames?[label]
  630. valueType._rlmProperty(property)
  631. value._rlmProperty(property)
  632. if let objcProp = class_getProperty(cls, label) {
  633. var count: UInt32 = 0
  634. let attrs = property_copyAttributeList(objcProp, &count)!
  635. defer {
  636. free(attrs)
  637. }
  638. var computed = true
  639. for i in 0..<Int(count) {
  640. let attr = attrs[i]
  641. switch attr.name[0] {
  642. case Int8(UInt8(ascii: "R")): // Read only
  643. return nil
  644. case Int8(UInt8(ascii: "V")): // Ivar name
  645. computed = false
  646. case Int8(UInt8(ascii: "G")): // Getter name
  647. property.getterName = String(cString: attr.value)
  648. case Int8(UInt8(ascii: "S")): // Setter name
  649. property.setterName = String(cString: attr.value)
  650. default:
  651. break
  652. }
  653. }
  654. // If there's no ivar name and no ivar with the same name as
  655. // the property then this is a computed property and we should
  656. // implicitly ignore it
  657. if computed && class_getInstanceVariable(cls, label) == nil {
  658. return nil
  659. }
  660. } else if valueType._rlmRequireObjc() {
  661. // Implicitly ignore non-@objc dynamic properties
  662. return nil
  663. } else {
  664. property.swiftIvar = class_getInstanceVariable(cls, label)
  665. }
  666. property.updateAccessors()
  667. return property
  668. }
  669. }
  670. }
  671. // MARK: AssistedObjectiveCBridgeable
  672. // FIXME: Remove when `as! Self` can be written
  673. private func forceCastToInferred<T, V>(_ x: T) -> V {
  674. return x as! V
  675. }
  676. extension Object: AssistedObjectiveCBridgeable {
  677. internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self {
  678. return forceCastToInferred(objectiveCValue)
  679. }
  680. internal var bridged: (objectiveCValue: Any, metadata: Any?) {
  681. return (objectiveCValue: unsafeCastToRLMObject(), metadata: nil)
  682. }
  683. }