123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787 |
- import Foundation
- import Realm
- import Realm.Private
- @objc(RealmSwiftObject)
- open class Object: RLMObjectBase, ThreadConfined, RealmCollectionValue {
-
- public static func _rlmArray() -> RLMArray<AnyObject> {
- return RLMArray(objectClassName: className())
- }
-
-
- public override required init() {
- super.init()
- }
-
- public convenience init(value: Any) {
- self.init()
- RLMInitializeWithValue(self, value, .partialPrivateShared())
- }
-
-
- public var realm: Realm? {
- if let rlmReam = RLMObjectBaseRealm(self) {
- return Realm(rlmReam)
- }
- return nil
- }
-
- public var objectSchema: ObjectSchema {
- return ObjectSchema(RLMObjectBaseObjectSchema(self)!)
- }
-
-
-
-
- public override final var isInvalidated: Bool { return super.isInvalidated }
-
- open override var description: String { return super.description }
-
- public override final class func _getProperties(withInstance instance: Any) -> [RLMProperty] {
- return ObjectUtil.getSwiftProperties(instance as! RLMObjectBase)
- }
-
-
- @objc open class func primaryKey() -> String? { return nil }
-
- @objc open class func ignoredProperties() -> [String] { return [] }
-
- @objc open class func indexedProperties() -> [String] { return [] }
-
-
- @objc open subscript(key: String) -> Any? {
- get {
- if realm == nil {
- return value(forKey: key)
- }
- return dynamicGet(key: key)
- }
- set(value) {
- if realm == nil {
- setValue(value, forKey: key)
- } else {
- RLMDynamicValidatedSet(self, key, value)
- }
- }
- }
- private func dynamicGet(key: String) -> Any? {
- let objectSchema = RLMObjectBaseObjectSchema(self)!
- guard let prop = objectSchema[key] else {
- throwRealmException("Invalid property name '\(key) for class \(objectSchema.className)")
- }
- if let accessor = prop.swiftAccessor {
- return accessor.get(Unmanaged.passUnretained(self).toOpaque() + ivar_getOffset(prop.swiftIvar!))
- }
- if let ivar = prop.swiftIvar, prop.array {
- return object_getIvar(self, ivar)
- }
- return RLMDynamicGet(self, prop)
- }
-
-
- public func observe(_ block: @escaping (ObjectChange) -> Void) -> NotificationToken {
- return RLMObjectAddNotificationBlock(self, { names, oldValues, newValues, error in
- if let error = error {
- block(.error(error as NSError))
- return
- }
- guard let names = names, let newValues = newValues else {
- block(.deleted)
- return
- }
- block(.change((0..<newValues.count).map { i in
- PropertyChange(name: names[i], oldValue: oldValues?[i], newValue: newValues[i])
- }))
- })
- }
-
-
- public func dynamicList(_ propertyName: String) -> List<DynamicObject> {
- return noWarnUnsafeBitCast(dynamicGet(key: propertyName) as! RLMListBase,
- to: List<DynamicObject>.self)
- }
-
-
- public func isSameObject(as object: Object?) -> Bool {
- return RLMObjectBaseAreEqual(self, object)
- }
- }
- public struct PropertyChange {
-
- public let name: String
-
- public let oldValue: Any?
-
- public let newValue: Any?
- }
- public enum ObjectChange {
-
- case error(_: NSError)
-
- case change(_: [PropertyChange])
-
- case deleted
- }
- public final class DynamicObject: Object {
- public override subscript(key: String) -> Any? {
- get {
- let value = RLMDynamicGetByName(self, key)
- if let array = value as? RLMArray<AnyObject> {
- return List<DynamicObject>(rlmArray: array)
- }
- return value
- }
- set(value) {
- RLMDynamicValidatedSet(self, key, value)
- }
- }
-
- public override func dynamicList(_ propertyName: String) -> List<DynamicObject> {
- return self[propertyName] as! List<DynamicObject>
- }
-
- public override func value(forUndefinedKey key: String) -> Any? {
- return self[key]
- }
-
- public override func setValue(_ value: Any?, forUndefinedKey key: String) {
- self[key] = value
- }
-
- public override class func shouldIncludeInDefaultSchema() -> Bool {
- return false
- }
- }
- public protocol RealmEnum: RealmOptionalType, _ManagedPropertyType {
-
-
- static func _rlmToRawValue(_ value: Any) -> Any
-
-
- static func _rlmFromRawValue(_ value: Any) -> Any
- }
- public extension RealmEnum where Self: RawRepresentable, Self.RawValue: _ManagedPropertyType {
-
- static func _rlmToRawValue(_ value: Any) -> Any {
- return (value as! Self).rawValue
- }
-
- static func _rlmFromRawValue(_ value: Any) -> Any {
- return Self.init(rawValue: value as! RawValue)!
- }
-
- static func _rlmProperty(_ prop: RLMProperty) {
- RawValue._rlmProperty(prop)
- }
- }
- public protocol _ManagedPropertyType {
-
- func _rlmProperty(_ prop: RLMProperty)
-
- static func _rlmProperty(_ prop: RLMProperty)
-
- static func _rlmRequireObjc() -> Bool
- }
- extension _ManagedPropertyType {
-
- public func _rlmProperty(_ prop: RLMProperty) { }
-
- public static func _rlmRequireObjc() -> Bool { return true }
- }
- extension Int: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .int
- }
- }
- extension Int8: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .int
- }
- }
- extension Int16: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .int
- }
- }
- extension Int32: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .int
- }
- }
- extension Int64: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .int
- }
- }
- extension Float: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .float
- }
- }
- extension Double: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .double
- }
- }
- extension Bool: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .bool
- }
- }
- extension String: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .string
- }
- }
- extension NSString: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .string
- }
- }
- extension Data: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .data
- }
- }
- extension NSData: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .data
- }
- }
- extension Date: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .date
- }
- }
- extension NSDate: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.type = .date
- }
- }
- extension Object: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- if !prop.optional && !prop.array {
- throwRealmException("Object property '\(prop.name)' must be marked as optional.")
- }
- if prop.optional && prop.array {
- throwRealmException("List<\(className())> property '\(prop.name)' must not be marked as optional.")
- }
- prop.type = .object
- prop.objectClassName = className()
- }
- }
- extension List: _ManagedPropertyType where Element: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.array = true
- Element._rlmProperty(prop)
- }
-
- public static func _rlmRequireObjc() -> Bool { return false }
- }
- class LinkingObjectsAccessor<Element: Object>: RLMManagedPropertyAccessor {
- @objc override class func initializeObject(_ ptr: UnsafeMutableRawPointer,
- parent: RLMObjectBase, property: RLMProperty) {
- ptr.assumingMemoryBound(to: LinkingObjects.self).pointee.handle = RLMLinkingObjectsHandle(object: parent, property: property)
- }
- @objc override class func get(_ ptr: UnsafeMutableRawPointer) -> Any {
- return ptr.assumingMemoryBound(to: LinkingObjects<Element>.self).pointee
- }
- }
- extension LinkingObjects: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.array = true
- prop.type = .linkingObjects
- prop.objectClassName = Element.className()
- prop.swiftAccessor = LinkingObjectsAccessor<Element>.self
- }
-
- public func _rlmProperty(_ prop: RLMProperty) {
- prop.linkOriginPropertyName = self.propertyName
- }
-
- public static func _rlmRequireObjc() -> Bool { return false }
- }
- extension Optional: _ManagedPropertyType where Wrapped: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.optional = true
- Wrapped._rlmProperty(prop)
- }
- }
- extension RealmOptional: _ManagedPropertyType where Value: _ManagedPropertyType {
-
- public static func _rlmProperty(_ prop: RLMProperty) {
- prop.optional = true
- Value._rlmProperty(prop)
- }
-
- public static func _rlmRequireObjc() -> Bool { return false }
- }
- internal class ObjectUtil {
- private static let runOnce: Void = {
- RLMSwiftAsFastEnumeration = { (obj: Any) -> Any? in
-
- if let collection = obj as AnyObject as? _RealmCollectionEnumerator {
- return collection._asNSFastEnumerator()
- }
- return nil
- }
- }()
- private class func swiftVersion() -> NSString {
- #if SWIFT_PACKAGE
- return "5.1"
- #else
- return swiftLanguageVersion as NSString
- #endif
- }
-
-
- private static func baseName(forLazySwiftProperty name: String) -> String? {
-
-
-
- if let storageRange = name.range(of: ".storage", options: [.anchored, .backwards]) {
- return String(name[..<storageRange.lowerBound])
- }
-
- if let storageRange = name.range(of: "$__lazy_storage_$_", options: [.anchored]) {
- return String(name[storageRange.upperBound...])
- }
- return nil
- }
-
- private static func getNonIgnoredMirrorChildren(for object: Any) -> [Mirror.Child] {
- let ignoredPropNames: Set<String>
- if let realmObject = object as? Object {
- ignoredPropNames = Set(type(of: realmObject).ignoredProperties())
- } else {
- ignoredPropNames = Set()
- }
- return Mirror(reflecting: object).children.filter { (prop: Mirror.Child) -> Bool in
- guard let label = prop.label else {
- return false
- }
- if ignoredPropNames.contains(label) {
- return false
- }
- if let lazyBaseName = baseName(forLazySwiftProperty: label) {
- if ignoredPropNames.contains(lazyBaseName) {
- return false
- }
-
-
- throwRealmException("Lazy managed property '\(lazyBaseName)' is not allowed on a Realm Swift object"
- + " class. Either add the property to the ignored properties list or make it non-lazy.")
- }
- return true
- }
- }
- internal class func getSwiftProperties(_ object: RLMObjectBase) -> [RLMProperty] {
- _ = ObjectUtil.runOnce
- let cls = type(of: object)
- var indexedProperties: Set<String>!
- let columnNames = cls._realmColumnNames()
- if let realmObject = object as? Object {
- indexedProperties = Set(type(of: realmObject).indexedProperties())
- } else {
- indexedProperties = Set()
- }
- return getNonIgnoredMirrorChildren(for: object).compactMap { prop in
- guard let label = prop.label else { return nil }
- var rawValue = prop.value
- if let value = rawValue as? RealmEnum {
- rawValue = type(of: value)._rlmToRawValue(value)
- }
- guard let value = rawValue as? _ManagedPropertyType else {
- if class_getProperty(cls, label) != nil {
- 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.")
- }
- if prop.value as? RealmOptionalProtocol != nil {
- throwRealmException("Property \(cls).\(label) has unsupported RealmOptional type \(type(of: prop.value)). Extending RealmOptionalType with custom types is not currently supported. ")
- }
- return nil
- }
- RLMValidateSwiftPropertyName(label)
- let valueType = type(of: value)
- let property = RLMProperty()
- property.name = label
- property.indexed = indexedProperties.contains(label)
- property.columnName = columnNames?[label]
- valueType._rlmProperty(property)
- value._rlmProperty(property)
- if let objcProp = class_getProperty(cls, label) {
- var count: UInt32 = 0
- let attrs = property_copyAttributeList(objcProp, &count)!
- defer {
- free(attrs)
- }
- var computed = true
- for i in 0..<Int(count) {
- let attr = attrs[i]
- switch attr.name[0] {
- case Int8(UInt8(ascii: "R")):
- return nil
- case Int8(UInt8(ascii: "V")):
- computed = false
- case Int8(UInt8(ascii: "G")):
- property.getterName = String(cString: attr.value)
- case Int8(UInt8(ascii: "S")):
- property.setterName = String(cString: attr.value)
- default:
- break
- }
- }
-
-
-
- if computed && class_getInstanceVariable(cls, label) == nil {
- return nil
- }
- } else if valueType._rlmRequireObjc() {
-
- return nil
- } else {
- property.swiftIvar = class_getInstanceVariable(cls, label)
- }
- property.updateAccessors()
- return property
- }
- }
- }
- private func forceCastToInferred<T, V>(_ x: T) -> V {
- return x as! V
- }
- extension Object: AssistedObjectiveCBridgeable {
- internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self {
- return forceCastToInferred(objectiveCValue)
- }
- internal var bridged: (objectiveCValue: Any, metadata: Any?) {
- return (objectiveCValue: unsafeCastToRLMObject(), metadata: nil)
- }
- }
|