RLMObjectBase.mm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 "RLMObject_Private.hpp"
  19. #import "RLMAccessor.h"
  20. #import "RLMArray_Private.hpp"
  21. #import "RLMListBase.h"
  22. #import "RLMObjectSchema_Private.hpp"
  23. #import "RLMObjectStore.h"
  24. #import "RLMObservation.hpp"
  25. #import "RLMOptionalBase.h"
  26. #import "RLMProperty_Private.h"
  27. #import "RLMRealm_Private.hpp"
  28. #import "RLMSchema_Private.h"
  29. #import "RLMSwiftSupport.h"
  30. #import "RLMThreadSafeReference_Private.hpp"
  31. #import "RLMUtil.hpp"
  32. #import "object.hpp"
  33. #import "object_schema.hpp"
  34. #import "shared_realm.hpp"
  35. using namespace realm;
  36. const NSUInteger RLMDescriptionMaxDepth = 5;
  37. static bool isManagedAccessorClass(Class cls) {
  38. const char *className = class_getName(cls);
  39. const char accessorClassPrefix[] = "RLM:Managed";
  40. return strncmp(className, accessorClassPrefix, sizeof(accessorClassPrefix) - 1) == 0;
  41. }
  42. static bool maybeInitObjectSchemaForUnmanaged(RLMObjectBase *obj) {
  43. Class cls = obj.class;
  44. if (isManagedAccessorClass(cls)) {
  45. return false;
  46. }
  47. obj->_objectSchema = [cls sharedSchema];
  48. if (!obj->_objectSchema) {
  49. return false;
  50. }
  51. // set default values
  52. if (!obj->_objectSchema.isSwiftClass) {
  53. NSDictionary *dict = RLMDefaultValuesForObjectSchema(obj->_objectSchema);
  54. for (NSString *key in dict) {
  55. [obj setValue:dict[key] forKey:key];
  56. }
  57. }
  58. // set unmanaged accessor class
  59. object_setClass(obj, obj->_objectSchema.unmanagedClass);
  60. return true;
  61. }
  62. @interface RLMObjectBase () <RLMThreadConfined, RLMThreadConfined_Private>
  63. @end
  64. @implementation RLMObjectBase
  65. // unmanaged init
  66. - (instancetype)init {
  67. if ((self = [super init])) {
  68. maybeInitObjectSchemaForUnmanaged(self);
  69. }
  70. return self;
  71. }
  72. - (void)dealloc {
  73. // This can't be a unique_ptr because associated objects are removed
  74. // *after* c++ members are destroyed and dealloc is called, and we need it
  75. // to be in a validish state when that happens
  76. delete _observationInfo;
  77. _observationInfo = nullptr;
  78. }
  79. static id coerceToObjectType(id obj, Class cls, RLMSchema *schema) {
  80. if ([obj isKindOfClass:cls]) {
  81. return obj;
  82. }
  83. id value = [[cls alloc] init];
  84. RLMInitializeWithValue(value, obj, schema);
  85. return value;
  86. }
  87. static id validatedObjectForProperty(__unsafe_unretained id const obj,
  88. __unsafe_unretained RLMObjectSchema *const objectSchema,
  89. __unsafe_unretained RLMProperty *const prop,
  90. __unsafe_unretained RLMSchema *const schema) {
  91. RLMValidateValueForProperty(obj, objectSchema, prop);
  92. if (!obj || obj == NSNull.null) {
  93. return nil;
  94. }
  95. if (prop.type == RLMPropertyTypeObject) {
  96. Class objectClass = schema[prop.objectClassName].objectClass;
  97. if (prop.array) {
  98. NSMutableArray *ret = [[NSMutableArray alloc] init];
  99. for (id el in obj) {
  100. [ret addObject:coerceToObjectType(el, objectClass, schema)];
  101. }
  102. return ret;
  103. }
  104. return coerceToObjectType(obj, objectClass, schema);
  105. }
  106. return obj;
  107. }
  108. void RLMInitializeWithValue(RLMObjectBase *self, id value, RLMSchema *schema) {
  109. if (!value || value == NSNull.null) {
  110. @throw RLMException(@"Must provide a non-nil value.");
  111. }
  112. RLMObjectSchema *objectSchema = self->_objectSchema;
  113. if (!objectSchema) {
  114. // Will be nil if we're called during schema init, when we don't want
  115. // to actually populate the object anyway
  116. return;
  117. }
  118. NSArray *properties = objectSchema.properties;
  119. if (NSArray *array = RLMDynamicCast<NSArray>(value)) {
  120. if (array.count > properties.count) {
  121. @throw RLMException(@"Invalid array input: more values (%llu) than properties (%llu).",
  122. (unsigned long long)array.count, (unsigned long long)properties.count);
  123. }
  124. NSUInteger i = 0;
  125. for (id val in array) {
  126. RLMProperty *prop = properties[i++];
  127. [self setValue:validatedObjectForProperty(RLMCoerceToNil(val), objectSchema, prop, schema)
  128. forKey:prop.name];
  129. }
  130. }
  131. else {
  132. // assume our object is an NSDictionary or an object with kvc properties
  133. for (RLMProperty *prop in properties) {
  134. id obj = RLMValidatedValueForProperty(value, prop.name, objectSchema.className);
  135. // don't set unspecified properties
  136. if (!obj) {
  137. continue;
  138. }
  139. [self setValue:validatedObjectForProperty(RLMCoerceToNil(obj), objectSchema, prop, schema)
  140. forKey:prop.name];
  141. }
  142. }
  143. }
  144. id RLMCreateManagedAccessor(Class cls, RLMClassInfo *info) {
  145. RLMObjectBase *obj = [[cls alloc] init];
  146. obj->_info = info;
  147. obj->_realm = info->realm;
  148. obj->_objectSchema = info->rlmObjectSchema;
  149. return obj;
  150. }
  151. - (id)valueForKey:(NSString *)key {
  152. if (_observationInfo) {
  153. return _observationInfo->valueForKey(key);
  154. }
  155. return [super valueForKey:key];
  156. }
  157. // Generic Swift properties can't be dynamic, so KVO doesn't work for them by default
  158. - (id)valueForUndefinedKey:(NSString *)key {
  159. RLMProperty *prop = _objectSchema[key];
  160. if (Class accessor = prop.swiftAccessor) {
  161. return [accessor get:(char *)(__bridge void *)self + ivar_getOffset(prop.swiftIvar)];
  162. }
  163. if (Ivar ivar = prop.swiftIvar) {
  164. return RLMCoerceToNil(object_getIvar(self, ivar));
  165. }
  166. return [super valueForUndefinedKey:key];
  167. }
  168. - (void)setValue:(id)value forUndefinedKey:(NSString *)key {
  169. value = RLMCoerceToNil(value);
  170. RLMProperty *property = _objectSchema[key];
  171. if (Ivar ivar = property.swiftIvar) {
  172. if (property.array) {
  173. value = RLMAsFastEnumeration(value);
  174. RLMArray *array = [object_getIvar(self, ivar) _rlmArray];
  175. [array removeAllObjects];
  176. if (value) {
  177. [array addObjects:validatedObjectForProperty(value, _objectSchema, property,
  178. RLMSchema.partialPrivateSharedSchema)];
  179. }
  180. }
  181. else if (property.optional) {
  182. RLMSetOptional(object_getIvar(self, ivar), value);
  183. }
  184. return;
  185. }
  186. [super setValue:value forUndefinedKey:key];
  187. }
  188. // overridden at runtime per-class for performance
  189. + (NSString *)className {
  190. NSString *className = NSStringFromClass(self);
  191. if ([RLMSwiftSupport isSwiftClassName:className]) {
  192. className = [RLMSwiftSupport demangleClassName:className];
  193. }
  194. return className;
  195. }
  196. // overridden at runtime per-class for performance
  197. + (RLMObjectSchema *)sharedSchema {
  198. return [RLMSchema sharedSchemaForClass:self.class];
  199. }
  200. + (void)initializeLinkedObjectSchemas {
  201. for (RLMProperty *prop in self.sharedSchema.properties) {
  202. if (prop.type == RLMPropertyTypeObject && !RLMSchema.partialPrivateSharedSchema[prop.objectClassName]) {
  203. [[RLMSchema classForString:prop.objectClassName] initializeLinkedObjectSchemas];
  204. }
  205. }
  206. }
  207. + (nullable NSArray<RLMProperty *> *)_getPropertiesWithInstance:(__unused id)obj {
  208. return nil;
  209. }
  210. - (NSString *)description {
  211. if (self.isInvalidated) {
  212. return @"[invalid object]";
  213. }
  214. return [self descriptionWithMaxDepth:RLMDescriptionMaxDepth];
  215. }
  216. - (NSString *)descriptionWithMaxDepth:(NSUInteger)depth {
  217. if (depth == 0) {
  218. return @"<Maximum depth exceeded>";
  219. }
  220. NSString *baseClassName = _objectSchema.className;
  221. NSMutableString *mString = [NSMutableString stringWithFormat:@"%@ {\n", baseClassName];
  222. for (RLMProperty *property in _objectSchema.properties) {
  223. id object = [(id)self objectForKeyedSubscript:property.name];
  224. NSString *sub;
  225. if ([object respondsToSelector:@selector(descriptionWithMaxDepth:)]) {
  226. sub = [object descriptionWithMaxDepth:depth - 1];
  227. }
  228. else if (property.type == RLMPropertyTypeData) {
  229. static NSUInteger maxPrintedDataLength = 24;
  230. NSData *data = object;
  231. NSUInteger length = data.length;
  232. if (length > maxPrintedDataLength) {
  233. data = [NSData dataWithBytes:data.bytes length:maxPrintedDataLength];
  234. }
  235. NSString *dataDescription = [data description];
  236. sub = [NSString stringWithFormat:@"<%@ — %lu total bytes>", [dataDescription substringWithRange:NSMakeRange(1, dataDescription.length - 2)], (unsigned long)length];
  237. }
  238. else {
  239. sub = [object description];
  240. }
  241. [mString appendFormat:@"\t%@ = %@;\n", property.name, [sub stringByReplacingOccurrencesOfString:@"\n" withString:@"\n\t"]];
  242. }
  243. [mString appendString:@"}"];
  244. return [NSString stringWithString:mString];
  245. }
  246. - (RLMRealm *)realm {
  247. return _realm;
  248. }
  249. - (RLMObjectSchema *)objectSchema {
  250. return _objectSchema;
  251. }
  252. - (BOOL)isInvalidated {
  253. // if not unmanaged and our accessor has been detached, we have been deleted
  254. return self.class == _objectSchema.accessorClass && !_row.is_attached();
  255. }
  256. - (BOOL)isEqual:(id)object {
  257. if (RLMObjectBase *other = RLMDynamicCast<RLMObjectBase>(object)) {
  258. if (_objectSchema.primaryKeyProperty) {
  259. return RLMObjectBaseAreEqual(self, other);
  260. }
  261. }
  262. return [super isEqual:object];
  263. }
  264. - (NSUInteger)hash {
  265. if (_objectSchema.primaryKeyProperty) {
  266. id primaryProperty = [self valueForKey:_objectSchema.primaryKeyProperty.name];
  267. // modify the hash of our primary key value to avoid potential (although unlikely) collisions
  268. return [primaryProperty hash] ^ 1;
  269. }
  270. else {
  271. return [super hash];
  272. }
  273. }
  274. + (BOOL)shouldIncludeInDefaultSchema {
  275. return RLMIsObjectSubclass(self);
  276. }
  277. + (NSString *)_realmObjectName {
  278. return nil;
  279. }
  280. + (NSDictionary *)_realmColumnNames {
  281. return nil;
  282. }
  283. + (bool)_realmIgnoreClass {
  284. return false;
  285. }
  286. - (id)mutableArrayValueForKey:(NSString *)key {
  287. id obj = [self valueForKey:key];
  288. if ([obj isKindOfClass:[RLMArray class]]) {
  289. return obj;
  290. }
  291. return [super mutableArrayValueForKey:key];
  292. }
  293. - (void)addObserver:(id)observer
  294. forKeyPath:(NSString *)keyPath
  295. options:(NSKeyValueObservingOptions)options
  296. context:(void *)context {
  297. if (!_observationInfo) {
  298. _observationInfo = new RLMObservationInfo(self);
  299. }
  300. _observationInfo->recordObserver(_row, _info, _objectSchema, keyPath);
  301. [super addObserver:observer forKeyPath:keyPath options:options context:context];
  302. }
  303. - (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath {
  304. [super removeObserver:observer forKeyPath:keyPath];
  305. if (_observationInfo)
  306. _observationInfo->removeObserver();
  307. }
  308. + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
  309. if (isManagedAccessorClass(self) && [class_getSuperclass(self.class) sharedSchema][key]) {
  310. return NO;
  311. }
  312. return [super automaticallyNotifiesObserversForKey:key];
  313. }
  314. #pragma mark - Thread Confined Protocol Conformance
  315. - (std::unique_ptr<realm::ThreadSafeReferenceBase>)makeThreadSafeReference {
  316. Object object(_realm->_realm, *_info->objectSchema, _row);
  317. realm::ThreadSafeReference<Object> reference = _realm->_realm->obtain_thread_safe_reference(std::move(object));
  318. return std::make_unique<realm::ThreadSafeReference<Object>>(std::move(reference));
  319. }
  320. - (id)objectiveCMetadata {
  321. return nil;
  322. }
  323. + (instancetype)objectWithThreadSafeReference:(std::unique_ptr<realm::ThreadSafeReferenceBase>)reference
  324. metadata:(__unused id)metadata
  325. realm:(RLMRealm *)realm {
  326. REALM_ASSERT_DEBUG(dynamic_cast<realm::ThreadSafeReference<Object> *>(reference.get()));
  327. auto object_reference = static_cast<realm::ThreadSafeReference<Object> *>(reference.get());
  328. Object object = realm->_realm->resolve_thread_safe_reference(std::move(*object_reference));
  329. if (!object.is_valid()) {
  330. return nil;
  331. }
  332. NSString *objectClassName = @(object.get_object_schema().name.c_str());
  333. return RLMCreateObjectAccessor(realm->_info[objectClassName], object.row().get_index());
  334. }
  335. @end
  336. RLMRealm *RLMObjectBaseRealm(__unsafe_unretained RLMObjectBase *object) {
  337. return object ? object->_realm : nil;
  338. }
  339. RLMObjectSchema *RLMObjectBaseObjectSchema(__unsafe_unretained RLMObjectBase *object) {
  340. return object ? object->_objectSchema : nil;
  341. }
  342. id RLMObjectBaseObjectForKeyedSubscript(RLMObjectBase *object, NSString *key) {
  343. if (!object) {
  344. return nil;
  345. }
  346. if (object->_realm) {
  347. return RLMDynamicGetByName(object, key);
  348. }
  349. else {
  350. return [object valueForKey:key];
  351. }
  352. }
  353. void RLMObjectBaseSetObjectForKeyedSubscript(RLMObjectBase *object, NSString *key, id obj) {
  354. if (!object) {
  355. return;
  356. }
  357. if (object->_realm || object.class == object->_objectSchema.accessorClass) {
  358. RLMDynamicValidatedSet(object, key, obj);
  359. }
  360. else {
  361. [object setValue:obj forKey:key];
  362. }
  363. }
  364. BOOL RLMObjectBaseAreEqual(RLMObjectBase *o1, RLMObjectBase *o2) {
  365. // if not the correct types throw
  366. if ((o1 && ![o1 isKindOfClass:RLMObjectBase.class]) || (o2 && ![o2 isKindOfClass:RLMObjectBase.class])) {
  367. @throw RLMException(@"Can only compare objects of class RLMObjectBase");
  368. }
  369. // if identical object (or both are nil)
  370. if (o1 == o2) {
  371. return YES;
  372. }
  373. // if one is nil
  374. if (o1 == nil || o2 == nil) {
  375. return NO;
  376. }
  377. // if not in realm or differing realms
  378. if (o1->_realm == nil || o1->_realm != o2->_realm) {
  379. return NO;
  380. }
  381. // if either are detached
  382. if (!o1->_row.is_attached() || !o2->_row.is_attached()) {
  383. return NO;
  384. }
  385. // if table and index are the same
  386. return o1->_row.get_table() == o2->_row.get_table()
  387. && o1->_row.get_index() == o2->_row.get_index();
  388. }
  389. id RLMValidatedValueForProperty(id object, NSString *key, NSString *className) {
  390. @try {
  391. return [object valueForKey:key];
  392. }
  393. @catch (NSException *e) {
  394. if ([e.name isEqualToString:NSUndefinedKeyException]) {
  395. @throw RLMException(@"Invalid value '%@' to initialize object of type '%@': missing key '%@'",
  396. object, className, key);
  397. }
  398. @throw;
  399. }
  400. }