RLMAccessor.mm 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  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 "RLMAccessor.hpp"
  19. #import "RLMArray_Private.hpp"
  20. #import "RLMListBase.h"
  21. #import "RLMObjectSchema_Private.hpp"
  22. #import "RLMObjectStore.h"
  23. #import "RLMObject_Private.hpp"
  24. #import "RLMObservation.hpp"
  25. #import "RLMProperty_Private.h"
  26. #import "RLMRealm_Private.hpp"
  27. #import "RLMResults_Private.hpp"
  28. #import "RLMSchema_Private.h"
  29. #import "RLMUtil.hpp"
  30. #import "results.hpp"
  31. #import "property.hpp"
  32. #import <objc/runtime.h>
  33. #import <objc/message.h>
  34. #import <realm/descriptor.hpp>
  35. #pragma mark - Helper functions
  36. namespace {
  37. template<typename T>
  38. T get(__unsafe_unretained RLMObjectBase *const obj, NSUInteger index) {
  39. RLMVerifyAttached(obj);
  40. return obj->_row.get<T>(obj->_info->objectSchema->persisted_properties[index].table_column);
  41. }
  42. template<typename T>
  43. id getBoxed(__unsafe_unretained RLMObjectBase *const obj, NSUInteger index) {
  44. RLMVerifyAttached(obj);
  45. auto& prop = obj->_info->objectSchema->persisted_properties[index];
  46. auto col = prop.table_column;
  47. if (obj->_row.is_null(col)) {
  48. return nil;
  49. }
  50. RLMAccessorContext ctx(obj, &prop);
  51. return ctx.box(obj->_row.get<T>(col));
  52. }
  53. template<typename T>
  54. void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex, T val) {
  55. RLMVerifyInWriteTransaction(obj);
  56. obj->_row.set(colIndex, val);
  57. }
  58. template<typename Fn>
  59. auto translateError(Fn&& fn) {
  60. try {
  61. return fn();
  62. }
  63. catch (std::exception const& e) {
  64. @throw RLMException(e);
  65. }
  66. }
  67. void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex,
  68. __unsafe_unretained NSString *const val) {
  69. RLMVerifyInWriteTransaction(obj);
  70. translateError([&] {
  71. obj->_row.set(colIndex, RLMStringDataWithNSString(val));
  72. });
  73. }
  74. [[gnu::noinline]]
  75. void setNull(realm::Row& row, size_t col) {
  76. translateError([&] { row.set_null(col); });
  77. }
  78. void setValue(__unsafe_unretained RLMObjectBase *const obj,
  79. NSUInteger colIndex, __unsafe_unretained NSDate *const date) {
  80. RLMVerifyInWriteTransaction(obj);
  81. if (date) {
  82. obj->_row.set(colIndex, RLMTimestampForNSDate(date));
  83. }
  84. else {
  85. setNull(obj->_row, colIndex);
  86. }
  87. }
  88. void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex,
  89. __unsafe_unretained NSData *const data) {
  90. RLMVerifyInWriteTransaction(obj);
  91. translateError([&] {
  92. obj->_row.set(colIndex, RLMBinaryDataForNSData(data));
  93. });
  94. }
  95. void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex,
  96. __unsafe_unretained RLMObjectBase *const val) {
  97. RLMVerifyInWriteTransaction(obj);
  98. if (!val) {
  99. obj->_row.nullify_link(colIndex);
  100. return;
  101. }
  102. RLMAddObjectToRealm(val, obj->_realm, RLMUpdatePolicyError);
  103. // make sure it is the correct type
  104. if (val->_row.get_table() != obj->_row.get_table()->get_link_target(colIndex)) {
  105. @throw RLMException(@"Can't set object of type '%@' to property of type '%@'",
  106. val->_objectSchema.className,
  107. obj->_info->propertyForTableColumn(colIndex).objectClassName);
  108. }
  109. obj->_row.set_link(colIndex, val->_row.get_index());
  110. }
  111. // array getter/setter
  112. RLMArray *getArray(__unsafe_unretained RLMObjectBase *const obj, NSUInteger propIndex) {
  113. RLMVerifyAttached(obj);
  114. auto prop = obj->_info->rlmObjectSchema.properties[propIndex];
  115. return [[RLMManagedArray alloc] initWithParent:obj property:prop];
  116. }
  117. void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex,
  118. __unsafe_unretained id<NSFastEnumeration> const value) {
  119. RLMVerifyInWriteTransaction(obj);
  120. auto prop = obj->_info->propertyForTableColumn(colIndex);
  121. RLMValidateValueForProperty(value, obj->_info->rlmObjectSchema, prop, true);
  122. realm::List list(obj->_realm->_realm, *obj->_row.get_table(), colIndex, obj->_row.get_index());
  123. RLMClassInfo *info = obj->_info;
  124. if (list.get_type() == realm::PropertyType::Object) {
  125. info = &obj->_info->linkTargetType(prop.index);
  126. }
  127. RLMAccessorContext ctx(*info);
  128. translateError([&] {
  129. list.assign(ctx, value, realm::CreatePolicy::ForceCreate);
  130. });
  131. }
  132. void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex,
  133. __unsafe_unretained NSNumber<RLMInt> *const intObject) {
  134. RLMVerifyInWriteTransaction(obj);
  135. if (intObject) {
  136. obj->_row.set(colIndex, intObject.longLongValue);
  137. }
  138. else {
  139. setNull(obj->_row, colIndex);
  140. }
  141. }
  142. void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex,
  143. __unsafe_unretained NSNumber<RLMFloat> *const floatObject) {
  144. RLMVerifyInWriteTransaction(obj);
  145. if (floatObject) {
  146. obj->_row.set(colIndex, floatObject.floatValue);
  147. }
  148. else {
  149. setNull(obj->_row, colIndex);
  150. }
  151. }
  152. void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex,
  153. __unsafe_unretained NSNumber<RLMDouble> *const doubleObject) {
  154. RLMVerifyInWriteTransaction(obj);
  155. if (doubleObject) {
  156. obj->_row.set(colIndex, doubleObject.doubleValue);
  157. }
  158. else {
  159. setNull(obj->_row, colIndex);
  160. }
  161. }
  162. void setValue(__unsafe_unretained RLMObjectBase *const obj, NSUInteger colIndex,
  163. __unsafe_unretained NSNumber<RLMBool> *const boolObject) {
  164. RLMVerifyInWriteTransaction(obj);
  165. if (boolObject) {
  166. obj->_row.set(colIndex, (bool)boolObject.boolValue);
  167. }
  168. else {
  169. setNull(obj->_row, colIndex);
  170. }
  171. }
  172. RLMLinkingObjects *getLinkingObjects(__unsafe_unretained RLMObjectBase *const obj,
  173. __unsafe_unretained RLMProperty *const property) {
  174. RLMVerifyAttached(obj);
  175. auto& objectInfo = obj->_realm->_info[property.objectClassName];
  176. auto& linkOrigin = obj->_info->objectSchema->computed_properties[property.index].link_origin_property_name;
  177. auto linkingProperty = objectInfo.objectSchema->property_for_name(linkOrigin);
  178. auto backlinkView = obj->_row.get_table()->get_backlink_view(obj->_row.get_index(),
  179. objectInfo.table(),
  180. linkingProperty->table_column);
  181. realm::Results results(obj->_realm->_realm, std::move(backlinkView));
  182. return [RLMLinkingObjects resultsWithObjectInfo:objectInfo results:std::move(results)];
  183. }
  184. // any getter/setter
  185. template<typename Type, typename StorageType=Type>
  186. id makeGetter(NSUInteger index) {
  187. return ^(__unsafe_unretained RLMObjectBase *const obj) {
  188. return static_cast<Type>(get<StorageType>(obj, index));
  189. };
  190. }
  191. template<typename Type>
  192. id makeBoxedGetter(NSUInteger index) {
  193. return ^(__unsafe_unretained RLMObjectBase *const obj) {
  194. return getBoxed<Type>(obj, index);
  195. };
  196. }
  197. template<typename Type>
  198. id makeOptionalGetter(NSUInteger index) {
  199. return ^(__unsafe_unretained RLMObjectBase *const obj) {
  200. return getBoxed<realm::util::Optional<Type>>(obj, index);
  201. };
  202. }
  203. template<typename Type>
  204. id makeNumberGetter(NSUInteger index, bool boxed, bool optional) {
  205. if (optional) {
  206. return makeOptionalGetter<Type>(index);
  207. }
  208. if (boxed) {
  209. return makeBoxedGetter<Type>(index);
  210. }
  211. return makeGetter<Type>(index);
  212. }
  213. // dynamic getter with column closure
  214. id managedGetter(RLMProperty *prop, const char *type) {
  215. NSUInteger index = prop.index;
  216. if (prop.array && prop.type != RLMPropertyTypeLinkingObjects) {
  217. return ^id(__unsafe_unretained RLMObjectBase *const obj) {
  218. return getArray(obj, index);
  219. };
  220. }
  221. bool boxed = *type == '@';
  222. switch (prop.type) {
  223. case RLMPropertyTypeInt:
  224. if (prop.optional || boxed) {
  225. return makeNumberGetter<long long>(index, boxed, prop.optional);
  226. }
  227. switch (*type) {
  228. case 'c': return makeGetter<char, int64_t>(index);
  229. case 's': return makeGetter<short, int64_t>(index);
  230. case 'i': return makeGetter<int, int64_t>(index);
  231. case 'l': return makeGetter<long, int64_t>(index);
  232. case 'q': return makeGetter<long long, int64_t>(index);
  233. default:
  234. @throw RLMException(@"Unexpected property type for Objective-C type code");
  235. }
  236. case RLMPropertyTypeFloat:
  237. return makeNumberGetter<float>(index, boxed, prop.optional);
  238. case RLMPropertyTypeDouble:
  239. return makeNumberGetter<double>(index, boxed, prop.optional);
  240. case RLMPropertyTypeBool:
  241. return makeNumberGetter<bool>(index, boxed, prop.optional);
  242. case RLMPropertyTypeString:
  243. return makeBoxedGetter<realm::StringData>(index);
  244. case RLMPropertyTypeDate:
  245. return makeBoxedGetter<realm::Timestamp>(index);
  246. case RLMPropertyTypeData:
  247. return makeBoxedGetter<realm::BinaryData>(index);
  248. case RLMPropertyTypeObject:
  249. return makeBoxedGetter<realm::RowExpr>(index);
  250. case RLMPropertyTypeAny:
  251. @throw RLMException(@"Cannot create accessor class for schema with Mixed properties");
  252. case RLMPropertyTypeLinkingObjects:
  253. return ^(__unsafe_unretained RLMObjectBase *const obj) {
  254. return getLinkingObjects(obj, prop);
  255. };
  256. }
  257. }
  258. template<typename ArgType, typename StorageType=ArgType>
  259. id makeSetter(__unsafe_unretained RLMProperty *const prop) {
  260. NSUInteger index = prop.index;
  261. NSString *name = prop.name;
  262. if (prop.isPrimary) {
  263. return ^(__unused RLMObjectBase *obj, __unused ArgType val) {
  264. @throw RLMException(@"Primary key can't be changed after an object is inserted.");
  265. };
  266. }
  267. return ^(__unsafe_unretained RLMObjectBase *const obj, ArgType val) {
  268. auto set = [&] {
  269. setValue(obj, obj->_info->objectSchema->persisted_properties[index].table_column,
  270. static_cast<StorageType>(val));
  271. };
  272. if (RLMObservationInfo *info = RLMGetObservationInfo(obj->_observationInfo,
  273. obj->_row.get_index(), *obj->_info)) {
  274. info->willChange(name);
  275. set();
  276. info->didChange(name);
  277. }
  278. else {
  279. set();
  280. }
  281. };
  282. }
  283. // dynamic setter with column closure
  284. id managedSetter(RLMProperty *prop, const char *type) {
  285. if (prop.array && prop.type != RLMPropertyTypeLinkingObjects) {
  286. return makeSetter<id<NSFastEnumeration>>(prop);
  287. }
  288. bool boxed = prop.optional || *type == '@';
  289. switch (prop.type) {
  290. case RLMPropertyTypeInt:
  291. if (boxed) {
  292. return makeSetter<NSNumber<RLMInt> *>(prop);
  293. }
  294. switch (*type) {
  295. case 'c': return makeSetter<char, long long>(prop);
  296. case 's': return makeSetter<short, long long>(prop);
  297. case 'i': return makeSetter<int, long long>(prop);
  298. case 'l': return makeSetter<long, long long>(prop);
  299. case 'q': return makeSetter<long long>(prop);
  300. default:
  301. @throw RLMException(@"Unexpected property type for Objective-C type code");
  302. }
  303. case RLMPropertyTypeFloat:
  304. return boxed ? makeSetter<NSNumber<RLMFloat> *>(prop) : makeSetter<float>(prop);
  305. case RLMPropertyTypeDouble:
  306. return boxed ? makeSetter<NSNumber<RLMDouble> *>(prop) : makeSetter<double>(prop);
  307. case RLMPropertyTypeBool:
  308. return boxed ? makeSetter<NSNumber<RLMBool> *>(prop) : makeSetter<BOOL, bool>(prop);
  309. case RLMPropertyTypeString: return makeSetter<NSString *>(prop);
  310. case RLMPropertyTypeDate: return makeSetter<NSDate *>(prop);
  311. case RLMPropertyTypeData: return makeSetter<NSData *>(prop);
  312. case RLMPropertyTypeAny: return nil;
  313. case RLMPropertyTypeLinkingObjects: return nil;
  314. case RLMPropertyTypeObject: return makeSetter<RLMObjectBase *>(prop);
  315. }
  316. }
  317. // call getter for superclass for property at colIndex
  318. id superGet(RLMObjectBase *obj, NSString *propName) {
  319. typedef id (*getter_type)(RLMObjectBase *, SEL);
  320. RLMProperty *prop = obj->_objectSchema[propName];
  321. Class superClass = class_getSuperclass(obj.class);
  322. getter_type superGetter = (getter_type)[superClass instanceMethodForSelector:prop.getterSel];
  323. return superGetter(obj, prop.getterSel);
  324. }
  325. // call setter for superclass for property at colIndex
  326. void superSet(RLMObjectBase *obj, NSString *propName, id val) {
  327. typedef void (*setter_type)(RLMObjectBase *, SEL, RLMArray *ar);
  328. RLMProperty *prop = obj->_objectSchema[propName];
  329. Class superClass = class_getSuperclass(obj.class);
  330. setter_type superSetter = (setter_type)[superClass instanceMethodForSelector:prop.setterSel];
  331. superSetter(obj, prop.setterSel, val);
  332. }
  333. // getter/setter for unmanaged object
  334. id unmanagedGetter(RLMProperty *prop, const char *) {
  335. // only override getters for RLMArray and linking objects properties
  336. if (prop.type == RLMPropertyTypeLinkingObjects) {
  337. return ^(RLMObjectBase *) { return [RLMResults emptyDetachedResults]; };
  338. }
  339. if (prop.array) {
  340. NSString *propName = prop.name;
  341. if (prop.type == RLMPropertyTypeObject) {
  342. NSString *objectClassName = prop.objectClassName;
  343. return ^(RLMObjectBase *obj) {
  344. id val = superGet(obj, propName);
  345. if (!val) {
  346. val = [[RLMArray alloc] initWithObjectClassName:objectClassName];
  347. superSet(obj, propName, val);
  348. }
  349. return val;
  350. };
  351. }
  352. auto type = prop.type;
  353. auto optional = prop.optional;
  354. return ^(RLMObjectBase *obj) {
  355. id val = superGet(obj, propName);
  356. if (!val) {
  357. val = [[RLMArray alloc] initWithObjectType:type optional:optional];
  358. superSet(obj, propName, val);
  359. }
  360. return val;
  361. };
  362. }
  363. return nil;
  364. }
  365. id unmanagedSetter(RLMProperty *prop, const char *) {
  366. // Only RLMArray needs special handling for the unmanaged setter
  367. if (!prop.array) {
  368. return nil;
  369. }
  370. NSString *propName = prop.name;
  371. return ^(RLMObjectBase *obj, id<NSFastEnumeration> values) {
  372. auto prop = obj->_objectSchema[propName];
  373. RLMValidateValueForProperty(values, obj->_objectSchema, prop, true);
  374. // make copy when setting (as is the case for all other variants)
  375. RLMArray *ar;
  376. if (prop.type == RLMPropertyTypeObject)
  377. ar = [[RLMArray alloc] initWithObjectClassName:prop.objectClassName];
  378. else
  379. ar = [[RLMArray alloc] initWithObjectType:prop.type optional:prop.optional];
  380. [ar addObjects:values];
  381. superSet(obj, propName, ar);
  382. };
  383. }
  384. void addMethod(Class cls, __unsafe_unretained RLMProperty *const prop,
  385. id (*getter)(RLMProperty *, const char *),
  386. id (*setter)(RLMProperty *, const char *)) {
  387. SEL sel = prop.getterSel;
  388. auto getterMethod = class_getInstanceMethod(cls, sel);
  389. if (!getterMethod) {
  390. return;
  391. }
  392. const char *getterType = method_getTypeEncoding(getterMethod);
  393. if (id block = getter(prop, getterType)) {
  394. class_addMethod(cls, sel, imp_implementationWithBlock(block), getterType);
  395. }
  396. if (!(sel = prop.setterSel)) {
  397. return;
  398. }
  399. auto setterMethod = class_getInstanceMethod(cls, sel);
  400. if (!setterMethod) {
  401. return;
  402. }
  403. if (id block = setter(prop, getterType)) { // note: deliberately getterType as it's easier to grab the relevant type from
  404. class_addMethod(cls, sel, imp_implementationWithBlock(block), method_getTypeEncoding(setterMethod));
  405. }
  406. }
  407. Class createAccessorClass(Class objectClass,
  408. RLMObjectSchema *schema,
  409. const char *accessorClassName,
  410. id (*getterGetter)(RLMProperty *, const char *),
  411. id (*setterGetter)(RLMProperty *, const char *)) {
  412. REALM_ASSERT_DEBUG(RLMIsObjectOrSubclass(objectClass));
  413. // create and register proxy class which derives from object class
  414. Class accClass = objc_allocateClassPair(objectClass, accessorClassName, 0);
  415. if (!accClass) {
  416. // Class with that name already exists, so just return the pre-existing one
  417. // This should only happen for our standalone "accessors"
  418. return objc_lookUpClass(accessorClassName);
  419. }
  420. // override getters/setters for each propery
  421. for (RLMProperty *prop in schema.properties) {
  422. addMethod(accClass, prop, getterGetter, setterGetter);
  423. }
  424. for (RLMProperty *prop in schema.computedProperties) {
  425. addMethod(accClass, prop, getterGetter, setterGetter);
  426. }
  427. objc_registerClassPair(accClass);
  428. return accClass;
  429. }
  430. } // anonymous namespace
  431. #pragma mark - Public Interface
  432. Class RLMManagedAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema, const char *name) {
  433. return createAccessorClass(objectClass, schema, name, managedGetter, managedSetter);
  434. }
  435. Class RLMUnmanagedAccessorClassForObjectClass(Class objectClass, RLMObjectSchema *schema) {
  436. return createAccessorClass(objectClass, schema,
  437. [@"RLM:Unmanaged " stringByAppendingString:schema.className].UTF8String,
  438. unmanagedGetter, unmanagedSetter);
  439. }
  440. // implement the class method className on accessors to return the className of the
  441. // base object
  442. void RLMReplaceClassNameMethod(Class accessorClass, NSString *className) {
  443. Class metaClass = object_getClass(accessorClass);
  444. IMP imp = imp_implementationWithBlock(^(Class){ return className; });
  445. class_addMethod(metaClass, @selector(className), imp, "@@:");
  446. }
  447. // implement the shared schema method
  448. void RLMReplaceSharedSchemaMethod(Class accessorClass, RLMObjectSchema *schema) {
  449. Class metaClass = object_getClass(accessorClass);
  450. IMP imp = imp_implementationWithBlock(^(Class cls) {
  451. if (cls == accessorClass) {
  452. return schema;
  453. }
  454. // If we aren't being called directly on the class this was overriden
  455. // for, the class is either a subclass which we haven't initialized yet,
  456. // or it's a runtime-generated class which should use the parent's
  457. // schema. We check for the latter by checking if the immediate
  458. // descendent of the desired class is a class generated by us (there
  459. // may be further subclasses not generated by us for things like KVO).
  460. Class parent = class_getSuperclass(cls);
  461. while (parent != accessorClass) {
  462. cls = parent;
  463. parent = class_getSuperclass(cls);
  464. }
  465. static const char accessorClassPrefix[] = "RLM:";
  466. if (!strncmp(class_getName(cls), accessorClassPrefix, sizeof(accessorClassPrefix) - 1)) {
  467. return schema;
  468. }
  469. return [RLMSchema sharedSchemaForClass:cls];
  470. });
  471. class_addMethod(metaClass, @selector(sharedSchema), imp, "@@:");
  472. }
  473. void RLMDynamicValidatedSet(RLMObjectBase *obj, NSString *propName, id val) {
  474. RLMVerifyAttached(obj);
  475. RLMObjectSchema *schema = obj->_objectSchema;
  476. RLMProperty *prop = schema[propName];
  477. if (!prop) {
  478. @throw RLMException(@"Invalid property name '%@' for class '%@'.",
  479. propName, obj->_objectSchema.className);
  480. }
  481. if (prop.isPrimary) {
  482. @throw RLMException(@"Primary key can't be changed to '%@' after an object is inserted.", val);
  483. }
  484. RLMValidateValueForProperty(val, schema, prop, true);
  485. RLMDynamicSet(obj, prop, RLMCoerceToNil(val));
  486. }
  487. // Precondition: the property is not a primary key
  488. void RLMDynamicSet(__unsafe_unretained RLMObjectBase *const obj,
  489. __unsafe_unretained RLMProperty *const prop,
  490. __unsafe_unretained id const val) {
  491. REALM_ASSERT_DEBUG(!prop.isPrimary);
  492. realm::Object o(obj->_info->realm->_realm, *obj->_info->objectSchema, obj->_row);
  493. RLMAccessorContext c(obj);
  494. translateError([&] {
  495. o.set_property_value(c, prop.columnName.UTF8String, val ?: NSNull.null);
  496. });
  497. }
  498. id RLMDynamicGet(__unsafe_unretained RLMObjectBase *const obj, __unsafe_unretained RLMProperty *const prop) {
  499. realm::Object o(obj->_realm->_realm, *obj->_info->objectSchema, obj->_row);
  500. RLMAccessorContext c(obj);
  501. c.currentProperty = prop;
  502. return translateError([&] {
  503. return RLMCoerceToNil(o.get_property_value<id>(c, prop.columnName.UTF8String));
  504. });
  505. }
  506. id RLMDynamicGetByName(__unsafe_unretained RLMObjectBase *const obj,
  507. __unsafe_unretained NSString *const propName) {
  508. RLMProperty *prop = obj->_objectSchema[propName];
  509. if (!prop) {
  510. @throw RLMException(@"Invalid property name '%@' for class '%@'.",
  511. propName, obj->_objectSchema.className);
  512. }
  513. return RLMDynamicGet(obj, prop);
  514. }
  515. RLMAccessorContext::RLMAccessorContext(RLMAccessorContext& parent, realm::Property const& property)
  516. : _realm(parent._realm)
  517. , _info(property.type == realm::PropertyType::Object ? parent._info.linkTargetType(property) : parent._info)
  518. , _promote_existing(parent._promote_existing)
  519. {
  520. }
  521. RLMAccessorContext::RLMAccessorContext(RLMClassInfo& info, bool promote)
  522. : _realm(info.realm), _info(info), _promote_existing(promote)
  523. {
  524. }
  525. RLMAccessorContext::RLMAccessorContext(__unsafe_unretained RLMObjectBase *const parent,
  526. const realm::Property *prop)
  527. : _realm(parent->_realm)
  528. , _info(prop && prop->type == realm::PropertyType::Object ? parent->_info->linkTargetType(*prop)
  529. : *parent->_info)
  530. , _parentObject(parent)
  531. {
  532. }
  533. id RLMAccessorContext::defaultValue(__unsafe_unretained NSString *const key) {
  534. if (!_defaultValues) {
  535. _defaultValues = RLMDefaultValuesForObjectSchema(_info.rlmObjectSchema);
  536. }
  537. return _defaultValues[key];
  538. }
  539. id RLMAccessorContext::propertyValue(__unsafe_unretained id const obj, size_t propIndex,
  540. __unsafe_unretained RLMProperty *const prop) {
  541. // Property value from an NSArray
  542. if ([obj respondsToSelector:@selector(objectAtIndex:)]) {
  543. return propIndex < [obj count] ? [obj objectAtIndex:propIndex] : nil;
  544. }
  545. // Property value from an NSDictionary
  546. if ([obj respondsToSelector:@selector(objectForKey:)]) {
  547. return [obj objectForKey:prop.name];
  548. }
  549. // Property value from an instance of this object type
  550. id value;
  551. if ([obj isKindOfClass:_info.rlmObjectSchema.objectClass] && prop.swiftIvar) {
  552. if (prop.array) {
  553. return static_cast<RLMListBase *>(object_getIvar(obj, prop.swiftIvar))._rlmArray;
  554. }
  555. else { // optional
  556. value = RLMGetOptional(static_cast<RLMOptionalBase *>(object_getIvar(obj, prop.swiftIvar)));
  557. }
  558. }
  559. else {
  560. // Property value from some object that's KVC-compatible
  561. value = RLMValidatedValueForProperty(obj, [obj respondsToSelector:prop.getterSel] ? prop.getterName : prop.name,
  562. _info.rlmObjectSchema.className);
  563. }
  564. return value ?: NSNull.null;
  565. }
  566. id RLMAccessorContext::box(realm::List&& l) {
  567. REALM_ASSERT(_parentObject);
  568. REALM_ASSERT(currentProperty);
  569. return [[RLMManagedArray alloc] initWithList:std::move(l)
  570. parentInfo:_parentObject->_info
  571. property:currentProperty];
  572. }
  573. id RLMAccessorContext::box(realm::Object&& o) {
  574. REALM_ASSERT(currentProperty);
  575. return RLMCreateObjectAccessor(_info.linkTargetType(currentProperty.index), o.row());
  576. }
  577. id RLMAccessorContext::box(realm::RowExpr r) {
  578. return RLMCreateObjectAccessor(_info, r);
  579. }
  580. id RLMAccessorContext::box(realm::Results&& r) {
  581. REALM_ASSERT(currentProperty);
  582. return [RLMResults resultsWithObjectInfo:_realm->_info[currentProperty.objectClassName]
  583. results:std::move(r)];
  584. }
  585. template<>
  586. realm::Timestamp RLMAccessorContext::unbox(__unsafe_unretained id const value, realm::CreatePolicy, size_t) {
  587. id v = RLMCoerceToNil(value);
  588. return RLMTimestampForNSDate(v);
  589. }
  590. template<>
  591. bool RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) {
  592. return [v boolValue];
  593. }
  594. template<>
  595. double RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) {
  596. return [v doubleValue];
  597. }
  598. template<>
  599. float RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) {
  600. return [v floatValue];
  601. }
  602. template<>
  603. long long RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) {
  604. return [v longLongValue];
  605. }
  606. template<>
  607. realm::BinaryData RLMAccessorContext::unbox(id v, realm::CreatePolicy, size_t) {
  608. v = RLMCoerceToNil(v);
  609. return RLMBinaryDataForNSData(v);
  610. }
  611. template<>
  612. realm::StringData RLMAccessorContext::unbox(id v, realm::CreatePolicy, size_t) {
  613. v = RLMCoerceToNil(v);
  614. return RLMStringDataWithNSString(v);
  615. }
  616. template<typename Fn>
  617. static auto to_optional(__unsafe_unretained id const value, Fn&& fn) {
  618. id v = RLMCoerceToNil(value);
  619. return v && v != NSNull.null ? realm::util::make_optional(fn(v)) : realm::util::none;
  620. }
  621. template<>
  622. realm::util::Optional<bool> RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) {
  623. return to_optional(v, [&](__unsafe_unretained id v) { return (bool)[v boolValue]; });
  624. }
  625. template<>
  626. realm::util::Optional<double> RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) {
  627. return to_optional(v, [&](__unsafe_unretained id v) { return [v doubleValue]; });
  628. }
  629. template<>
  630. realm::util::Optional<float> RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) {
  631. return to_optional(v, [&](__unsafe_unretained id v) { return [v floatValue]; });
  632. }
  633. template<>
  634. realm::util::Optional<int64_t> RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy, size_t) {
  635. return to_optional(v, [&](__unsafe_unretained id v) { return [v longLongValue]; });
  636. }
  637. template<>
  638. realm::RowExpr RLMAccessorContext::unbox(__unsafe_unretained id const v, realm::CreatePolicy createPolicy, size_t) {
  639. bool create = createPolicy != realm::CreatePolicy::Skip;
  640. auto policy = static_cast<RLMUpdatePolicy>(createPolicy);
  641. RLMObjectBase *link = RLMDynamicCast<RLMObjectBase>(v);
  642. if (!link) {
  643. if (!create)
  644. return realm::RowExpr();
  645. return RLMCreateObjectInRealmWithValue(_realm, _info.rlmObjectSchema.className, v, policy)->_row;
  646. }
  647. if (link.isInvalidated) {
  648. if (create) {
  649. @throw RLMException(@"Adding a deleted or invalidated object to a Realm is not permitted");
  650. }
  651. else {
  652. @throw RLMException(@"Object has been invalidated");
  653. }
  654. }
  655. if (![link->_objectSchema.className isEqualToString:_info.rlmObjectSchema.className]) {
  656. if (create && !_promote_existing)
  657. return RLMCreateObjectInRealmWithValue(_realm, _info.rlmObjectSchema.className, link, policy)->_row;
  658. return link->_row;
  659. }
  660. if (!link->_realm) {
  661. if (!create)
  662. return realm::RowExpr();
  663. if (!_promote_existing)
  664. return RLMCreateObjectInRealmWithValue(_realm, _info.rlmObjectSchema.className, link, policy)->_row;
  665. RLMAddObjectToRealm(link, _realm, policy);
  666. }
  667. else if (link->_realm != _realm) {
  668. if (_promote_existing)
  669. @throw RLMException(@"Object is already managed by another Realm. Use create instead to copy it into this Realm.");
  670. return RLMCreateObjectInRealmWithValue(_realm, _info.rlmObjectSchema.className, v, policy)->_row;
  671. }
  672. return link->_row;
  673. }
  674. void RLMAccessorContext::will_change(realm::Row const& row, realm::Property const& prop) {
  675. _observationInfo = RLMGetObservationInfo(nullptr, row.get_index(), _info);
  676. if (_observationInfo) {
  677. _kvoPropertyName = _info.propertyForTableColumn(prop.table_column).name;
  678. _observationInfo->willChange(_kvoPropertyName);
  679. }
  680. }
  681. void RLMAccessorContext::did_change() {
  682. if (_observationInfo) {
  683. _observationInfo->didChange(_kvoPropertyName);
  684. _kvoPropertyName = nil;
  685. _observationInfo = nullptr;
  686. }
  687. }
  688. RLMOptionalId RLMAccessorContext::value_for_property(__unsafe_unretained id const obj,
  689. realm::Property const&, size_t propIndex) {
  690. auto prop = _info.rlmObjectSchema.properties[propIndex];
  691. id value = propertyValue(obj, propIndex, prop);
  692. if (value) {
  693. RLMValidateValueForProperty(value, _info.rlmObjectSchema, prop);
  694. }
  695. if (_promote_existing && [obj isKindOfClass:_info.rlmObjectSchema.objectClass] && !prop.swiftIvar) {
  696. // set the ivars for object and array properties to nil as otherwise the
  697. // accessors retain objects that are no longer accessible via the properties
  698. // this is mainly an issue when the object graph being added has cycles,
  699. // as it's not obvious that the user has to set the *ivars* to nil to
  700. // avoid leaking memory
  701. if (prop.type == RLMPropertyTypeObject) {
  702. ((void(*)(id, SEL, id))objc_msgSend)(obj, prop.setterSel, nil);
  703. }
  704. }
  705. return RLMOptionalId{value};
  706. }
  707. RLMOptionalId RLMAccessorContext::default_value_for_property(realm::ObjectSchema const&,
  708. realm::Property const& prop)
  709. {
  710. return RLMOptionalId{defaultValue(@(prop.name.c_str()))};
  711. }
  712. bool RLMAccessorContext::is_same_list(realm::List const& list, __unsafe_unretained id const v) const noexcept {
  713. return [v respondsToSelector:@selector(isBackedByList:)] && [v isBackedByList:list];
  714. }
  715. #pragma clang diagnostic push
  716. #pragma clang diagnostic ignored "-Wincomplete-implementation"
  717. @implementation RLMManagedPropertyAccessor
  718. @end
  719. #pragma clang diagnostic pop