RLMCollection.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2016 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 "RLMCollection_Private.hpp"
  19. #import "RLMAccessor.hpp"
  20. #import "RLMArray_Private.hpp"
  21. #import "RLMListBase.h"
  22. #import "RLMObjectSchema_Private.hpp"
  23. #import "RLMObjectStore.h"
  24. #import "RLMObject_Private.hpp"
  25. #import "RLMProperty_Private.h"
  26. #import "collection_notifications.hpp"
  27. #import "list.hpp"
  28. #import "results.hpp"
  29. static const int RLMEnumerationBufferSize = 16;
  30. @implementation RLMFastEnumerator {
  31. // The buffer supplied by fast enumeration does not retain the objects given
  32. // to it, but because we create objects on-demand and don't want them
  33. // autoreleased (a table can have more rows than the device has memory for
  34. // accessor objects) we need a thing to retain them.
  35. id _strongBuffer[RLMEnumerationBufferSize];
  36. RLMRealm *_realm;
  37. RLMClassInfo *_info;
  38. // A pointer to either _snapshot or a Results from the source collection,
  39. // to avoid having to copy the Results when not in a write transaction
  40. realm::Results *_results;
  41. realm::Results _snapshot;
  42. // A strong reference to the collection being enumerated to ensure it stays
  43. // alive when we're holding a pointer to a member in it
  44. id _collection;
  45. }
  46. - (instancetype)initWithList:(realm::List&)list
  47. collection:(id)collection
  48. classInfo:(RLMClassInfo&)info
  49. {
  50. self = [super init];
  51. if (self) {
  52. _info = &info;
  53. _realm = _info->realm;
  54. if (_realm.inWriteTransaction) {
  55. _snapshot = list.snapshot();
  56. }
  57. else {
  58. _snapshot = list.as_results();
  59. _collection = collection;
  60. [_realm registerEnumerator:self];
  61. }
  62. _results = &_snapshot;
  63. }
  64. return self;
  65. }
  66. - (instancetype)initWithResults:(realm::Results&)results
  67. collection:(id)collection
  68. classInfo:(RLMClassInfo&)info
  69. {
  70. self = [super init];
  71. if (self) {
  72. _info = &info;
  73. _realm = _info->realm;
  74. if (_realm.inWriteTransaction) {
  75. _snapshot = results.snapshot();
  76. _results = &_snapshot;
  77. }
  78. else {
  79. _results = &results;
  80. _collection = collection;
  81. [_realm registerEnumerator:self];
  82. }
  83. }
  84. return self;
  85. }
  86. - (void)dealloc {
  87. if (_collection) {
  88. [_realm unregisterEnumerator:self];
  89. }
  90. }
  91. - (void)detach {
  92. _snapshot = _results->snapshot();
  93. _results = &_snapshot;
  94. _collection = nil;
  95. }
  96. - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
  97. count:(NSUInteger)len {
  98. [_realm verifyThread];
  99. if (!_results->is_valid()) {
  100. @throw RLMException(@"Collection is no longer valid");
  101. }
  102. // The fast enumeration buffer size is currently a hardcoded number in the
  103. // compiler so this can't actually happen, but just in case it changes in
  104. // the future...
  105. if (len > RLMEnumerationBufferSize) {
  106. len = RLMEnumerationBufferSize;
  107. }
  108. NSUInteger batchCount = 0, count = state->extra[1];
  109. @autoreleasepool {
  110. RLMAccessorContext ctx(*_info);
  111. for (NSUInteger index = state->state; index < count && batchCount < len; ++index) {
  112. _strongBuffer[batchCount] = _results->get(ctx, index);
  113. batchCount++;
  114. }
  115. }
  116. for (NSUInteger i = batchCount; i < len; ++i) {
  117. _strongBuffer[i] = nil;
  118. }
  119. if (batchCount == 0) {
  120. // Release our data if we're done, as we're autoreleased and so may
  121. // stick around for a while
  122. if (_collection) {
  123. _collection = nil;
  124. [_realm unregisterEnumerator:self];
  125. }
  126. _snapshot = {};
  127. }
  128. state->itemsPtr = (__unsafe_unretained id *)(void *)_strongBuffer;
  129. state->state += batchCount;
  130. state->mutationsPtr = state->extra+1;
  131. return batchCount;
  132. }
  133. @end
  134. NSUInteger RLMFastEnumerate(NSFastEnumerationState *state, NSUInteger len, id<RLMFastEnumerable> collection) {
  135. __autoreleasing RLMFastEnumerator *enumerator;
  136. if (state->state == 0) {
  137. enumerator = collection.fastEnumerator;
  138. state->extra[0] = (long)enumerator;
  139. state->extra[1] = collection.count;
  140. }
  141. else {
  142. enumerator = (__bridge id)(void *)state->extra[0];
  143. }
  144. return [enumerator countByEnumeratingWithState:state count:len];
  145. }
  146. template<typename Collection>
  147. NSArray *RLMCollectionValueForKey(Collection& collection, NSString *key, RLMClassInfo& info) {
  148. size_t count = collection.size();
  149. if (count == 0) {
  150. return @[];
  151. }
  152. NSMutableArray *array = [NSMutableArray arrayWithCapacity:count];
  153. if ([key isEqualToString:@"self"]) {
  154. RLMAccessorContext context(info);
  155. for (size_t i = 0; i < count; ++i) {
  156. [array addObject:collection.get(context, i) ?: NSNull.null];
  157. }
  158. return array;
  159. }
  160. if (collection.get_type() != realm::PropertyType::Object) {
  161. RLMAccessorContext context(info);
  162. for (size_t i = 0; i < count; ++i) {
  163. [array addObject:[collection.get(context, i) valueForKey:key] ?: NSNull.null];
  164. }
  165. return array;
  166. }
  167. RLMObject *accessor = RLMCreateManagedAccessor(info.rlmObjectSchema.accessorClass, &info);
  168. // List properties need to be handled specially since we need to create a
  169. // new List each time
  170. if (info.rlmObjectSchema.isSwiftClass) {
  171. auto prop = info.rlmObjectSchema[key];
  172. if (prop && prop.array && prop.swiftIvar) {
  173. // Grab the actual class for the generic List from an instance of it
  174. // so that we can make instances of the List without creating a new
  175. // object accessor each time
  176. Class cls = [object_getIvar(accessor, prop.swiftIvar) class];
  177. RLMAccessorContext context(info);
  178. for (size_t i = 0; i < count; ++i) {
  179. RLMListBase *list = [[cls alloc] init];
  180. list._rlmArray = [[RLMManagedArray alloc] initWithList:realm::List(info.realm->_realm, *info.table(),
  181. info.tableColumn(prop),
  182. collection.get(i).get_index())
  183. parentInfo:&info
  184. property:prop];
  185. [array addObject:list];
  186. }
  187. return array;
  188. }
  189. }
  190. for (size_t i = 0; i < count; i++) {
  191. accessor->_row = collection.get(i);
  192. RLMInitializeSwiftAccessorGenerics(accessor);
  193. [array addObject:[accessor valueForKey:key] ?: NSNull.null];
  194. }
  195. return array;
  196. }
  197. template NSArray *RLMCollectionValueForKey(realm::Results&, NSString *, RLMClassInfo&);
  198. template NSArray *RLMCollectionValueForKey(realm::List&, NSString *, RLMClassInfo&);
  199. void RLMCollectionSetValueForKey(id<RLMFastEnumerable> collection, NSString *key, id value) {
  200. realm::TableView tv = [collection tableView];
  201. if (tv.size() == 0) {
  202. return;
  203. }
  204. RLMClassInfo *info = collection.objectInfo;
  205. RLMObject *accessor = RLMCreateManagedAccessor(info->rlmObjectSchema.accessorClass, info);
  206. for (size_t i = 0; i < tv.size(); i++) {
  207. accessor->_row = tv[i];
  208. RLMInitializeSwiftAccessorGenerics(accessor);
  209. [accessor setValue:value forKey:key];
  210. }
  211. }
  212. NSString *RLMDescriptionWithMaxDepth(NSString *name,
  213. id<RLMCollection> collection,
  214. NSUInteger depth) {
  215. if (depth == 0) {
  216. return @"<Maximum depth exceeded>";
  217. }
  218. const NSUInteger maxObjects = 100;
  219. auto str = [NSMutableString stringWithFormat:@"%@<%@> <%p> (\n", name,
  220. [collection objectClassName] ?: RLMTypeToString([collection type]),
  221. (void *)collection];
  222. size_t index = 0, skipped = 0;
  223. for (id obj in collection) {
  224. NSString *sub;
  225. if ([obj respondsToSelector:@selector(descriptionWithMaxDepth:)]) {
  226. sub = [obj descriptionWithMaxDepth:depth - 1];
  227. }
  228. else {
  229. sub = [obj description];
  230. }
  231. // Indent child objects
  232. NSString *objDescription = [sub stringByReplacingOccurrencesOfString:@"\n"
  233. withString:@"\n\t"];
  234. [str appendFormat:@"\t[%zu] %@,\n", index++, objDescription];
  235. if (index >= maxObjects) {
  236. skipped = collection.count - maxObjects;
  237. break;
  238. }
  239. }
  240. // Remove last comma and newline characters
  241. if (collection.count > 0) {
  242. [str deleteCharactersInRange:NSMakeRange(str.length-2, 2)];
  243. }
  244. if (skipped) {
  245. [str appendFormat:@"\n\t... %zu objects skipped.", skipped];
  246. }
  247. [str appendFormat:@"\n)"];
  248. return str;
  249. }
  250. std::vector<std::pair<std::string, bool>> RLMSortDescriptorsToKeypathArray(NSArray<RLMSortDescriptor *> *properties) {
  251. std::vector<std::pair<std::string, bool>> keypaths;
  252. keypaths.reserve(properties.count);
  253. for (RLMSortDescriptor *desc in properties) {
  254. if ([desc.keyPath rangeOfString:@"@"].location != NSNotFound) {
  255. @throw RLMException(@"Cannot sort on key path '%@': KVC collection operators are not supported.", desc.keyPath);
  256. }
  257. keypaths.push_back({desc.keyPath.UTF8String, desc.ascending});
  258. }
  259. return keypaths;
  260. }
  261. @implementation RLMCancellationToken {
  262. realm::NotificationToken _token;
  263. __unsafe_unretained RLMRealm *_realm;
  264. }
  265. - (instancetype)initWithToken:(realm::NotificationToken)token realm:(RLMRealm *)realm {
  266. self = [super init];
  267. if (self) {
  268. _token = std::move(token);
  269. _realm = realm;
  270. }
  271. return self;
  272. }
  273. - (RLMRealm *)realm {
  274. return _realm;
  275. }
  276. - (void)suppressNextNotification {
  277. _token.suppress_next();
  278. }
  279. - (void)invalidate {
  280. _token = {};
  281. }
  282. @end
  283. @implementation RLMCollectionChange {
  284. realm::CollectionChangeSet _indices;
  285. }
  286. - (instancetype)initWithChanges:(realm::CollectionChangeSet)indices {
  287. self = [super init];
  288. if (self) {
  289. _indices = std::move(indices);
  290. }
  291. return self;
  292. }
  293. static NSArray *toArray(realm::IndexSet const& set) {
  294. NSMutableArray *ret = [NSMutableArray new];
  295. for (auto index : set.as_indexes()) {
  296. [ret addObject:@(index)];
  297. }
  298. return ret;
  299. }
  300. - (NSArray *)insertions {
  301. return toArray(_indices.insertions);
  302. }
  303. - (NSArray *)deletions {
  304. return toArray(_indices.deletions);
  305. }
  306. - (NSArray *)modifications {
  307. return toArray(_indices.modifications);
  308. }
  309. static NSArray *toIndexPathArray(realm::IndexSet const& set, NSUInteger section) {
  310. NSMutableArray *ret = [NSMutableArray new];
  311. NSUInteger path[2] = {section, 0};
  312. for (auto index : set.as_indexes()) {
  313. path[1] = index;
  314. [ret addObject:[NSIndexPath indexPathWithIndexes:path length:2]];
  315. }
  316. return ret;
  317. }
  318. - (NSArray<NSIndexPath *> *)deletionsInSection:(NSUInteger)section {
  319. return toIndexPathArray(_indices.deletions, section);
  320. }
  321. - (NSArray<NSIndexPath *> *)insertionsInSection:(NSUInteger)section {
  322. return toIndexPathArray(_indices.insertions, section);
  323. }
  324. - (NSArray<NSIndexPath *> *)modificationsInSection:(NSUInteger)section {
  325. return toIndexPathArray(_indices.modifications, section);
  326. }
  327. @end
  328. template<typename Collection>
  329. RLMNotificationToken *RLMAddNotificationBlock(id objcCollection,
  330. Collection& collection,
  331. void (^block)(id, RLMCollectionChange *, NSError *),
  332. bool suppressInitialChange) {
  333. auto skip = suppressInitialChange ? std::make_shared<bool>(true) : nullptr;
  334. auto cb = [=, &collection](realm::CollectionChangeSet const& changes,
  335. std::exception_ptr err) {
  336. if (err) {
  337. try {
  338. rethrow_exception(err);
  339. }
  340. catch (...) {
  341. NSError *error = nil;
  342. RLMRealmTranslateException(&error);
  343. block(nil, nil, error);
  344. return;
  345. }
  346. }
  347. if (skip && *skip) {
  348. *skip = false;
  349. block(objcCollection, nil, nil);
  350. }
  351. else if (changes.empty()) {
  352. block(objcCollection, nil, nil);
  353. }
  354. else {
  355. block(objcCollection, [[RLMCollectionChange alloc] initWithChanges:changes], nil);
  356. }
  357. };
  358. return [[RLMCancellationToken alloc] initWithToken:collection.add_notification_callback(cb)
  359. realm:(RLMRealm *)[objcCollection realm]];
  360. }
  361. // Explicitly instantiate the templated function for the two types we'll use it on
  362. template RLMNotificationToken *RLMAddNotificationBlock<realm::List>(id, realm::List&, void (^)(id, RLMCollectionChange *, NSError *), bool);
  363. template RLMNotificationToken *RLMAddNotificationBlock<realm::Results>(id, realm::Results&, void (^)(id, RLMCollectionChange *, NSError *), bool);