RLMDictionary.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2021 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 <Realm/RLMCollection.h>
  19. RLM_HEADER_AUDIT_BEGIN(nullability, sendability)
  20. @class RLMObject, RLMResults<RLMObjectType>, RLMDictionaryChange;
  21. /**
  22. `RLMDictionary` is a container type in Realm representing a dynamic collection of key-value pairs.
  23. Unlike `NSDictionary`, `RLMDictionary`s hold a single key and value type.
  24. This is referred to in these docs as the “type” and “keyType” of the dictionary.
  25. When declaring an `RLMDictionary` property, the object type and keyType must be marked as conforming to a
  26. protocol by the same name as the objects it should contain.
  27. RLM_COLLECTION_TYPE(ObjectType)
  28. ...
  29. @property RLMDictionary<NSString *, ObjectType *><RLMString, ObjectType> *objectTypeDictionary;
  30. `RLMDictionary`s can be queried with the same predicates as `RLMObject` and `RLMResult`s.
  31. `RLMDictionary`s cannot be created directly. `RLMDictionary` properties on `RLMObject`s are
  32. lazily created when accessed, or can be obtained by querying a Realm.
  33. `RLMDictionary` only supports `NSString` as a key. Realm disallows the use of `.` or `$` characters within a dictionary key.
  34. ### Key-Value Observing
  35. `RLMDictionary` supports dictionary key-value observing on `RLMDictionary` properties on `RLMObject`
  36. subclasses, and the `invalidated` property on `RLMDictionary` instances themselves is
  37. key-value observing compliant when the `RLMDictionary` is attached to a managed
  38. `RLMObject` (`RLMDictionary`s on unmanaged `RLMObject`s will never become invalidated).
  39. */
  40. @interface RLMDictionary<RLMKeyType, RLMObjectType>: NSObject<RLMCollection>
  41. #pragma mark - Properties
  42. /**
  43. The number of entries in the dictionary.
  44. */
  45. @property (nonatomic, readonly, assign) NSUInteger count;
  46. /**
  47. The type of the objects in the dictionary.
  48. */
  49. @property (nonatomic, readonly, assign) RLMPropertyType type;
  50. /**
  51. The type of the key used in this dictionary.
  52. */
  53. @property (nonatomic, readonly, assign) RLMPropertyType keyType;
  54. /**
  55. Indicates whether the objects in the collection can be `nil`.
  56. */
  57. @property (nonatomic, readonly, getter = isOptional) BOOL optional;
  58. /**
  59. The class name of the objects contained in the dictionary.
  60. Will be `nil` if `type` is not RLMPropertyTypeObject.
  61. */
  62. @property (nonatomic, readonly, copy, nullable) NSString *objectClassName;
  63. /**
  64. The Realm which manages the dictionary. Returns `nil` for unmanaged dictionary.
  65. */
  66. @property (nonatomic, readonly, nullable) RLMRealm *realm;
  67. /**
  68. Indicates if the dictionary can no longer be accessed.
  69. */
  70. @property (nonatomic, readonly, getter = isInvalidated) BOOL invalidated;
  71. /**
  72. Indicates if the dictionary is frozen.
  73. Frozen dictionaries are immutable and can be accessed from any thread. Frozen dictionaries
  74. are created by calling `-freeze` on a managed live dictionary. Unmanaged dictionaries are
  75. never frozen.
  76. */
  77. @property (nonatomic, readonly, getter = isFrozen) BOOL frozen;
  78. #pragma mark - Accessing Objects from a Dictionary
  79. /**
  80. Returns the value associated with a given key.
  81. @param key The name of the property.
  82. @discussion If key does not start with “@”, invokes object(forKey:). If key does start
  83. with “@”, strips the “@” and invokes [super valueForKey:] with the rest of the key.
  84. @return A value associated with a given key or `nil`.
  85. */
  86. - (nullable id)valueForKey:(nonnull RLMKeyType)key;
  87. /**
  88. Returns an array containing the dictionary’s keys.
  89. @note The order of the elements in the array is not defined.
  90. */
  91. @property(readonly, copy) NSArray<RLMKeyType> *allKeys;
  92. /**
  93. Returns an array containing the dictionary’s values.
  94. @note The order of the elements in the array is not defined.
  95. */
  96. @property(readonly, copy) NSArray<RLMObjectType> *allValues;
  97. /**
  98. Returns the value associated with a given key.
  99. @note `nil` will be returned if no value is associated with a given key. NSNull will be returned
  100. where null is associated with the key.
  101. @param key The key for which to return the corresponding value.
  102. @return The value associated with key.
  103. */
  104. - (nullable RLMObjectType)objectForKey:(nonnull RLMKeyType)key;
  105. /**
  106. Returns the value associated with a given key.
  107. @note `nil` will be returned if no value is associated with a given key. NSNull will be returned
  108. where null is associated with the key.
  109. @param key The key for which to return the corresponding value.
  110. @return The value associated with key.
  111. */
  112. - (nullable RLMObjectType)objectForKeyedSubscript:(RLMKeyType)key;
  113. /**
  114. Applies a given block object to the each key-value pair of the dictionary.
  115. @param block A block object to operate on entries in the dictionary.
  116. @note If the block sets *stop to YES, the enumeration stops.
  117. */
  118. - (void)enumerateKeysAndObjectsUsingBlock:(void (^)(RLMKeyType key, RLMObjectType obj, BOOL *stop))block;
  119. #pragma mark - Adding, Removing, and Replacing Objects in a Dictionary
  120. /**
  121. Replace the contents of a dictionary with the contents of another dictionary - NSDictionary or RLMDictionary.
  122. This will remove all elements in this dictionary and then apply each element from the given dictionary.
  123. @warning This method may only be called during a write transaction.
  124. @warning If otherDictionary is self this will result in an empty dictionary.
  125. */
  126. - (void)setDictionary:(id)otherDictionary;
  127. /**
  128. Removes all contents in the dictionary.
  129. @warning This method may only be called during a write transaction.
  130. */
  131. - (void)removeAllObjects;
  132. /**
  133. Removes from the dictionary entries specified by elements in a given array. If a given key does not
  134. exist, no mutation will happen for that key.
  135. @warning This method may only be called during a write transaction.
  136. */
  137. - (void)removeObjectsForKeys:(NSArray<RLMKeyType> *)keyArray;
  138. /**
  139. Removes a given key and its associated value from the dictionary. If the key does not exist the dictionary
  140. will not be modified.
  141. @warning This method may only be called during a write transaction.
  142. */
  143. - (void)removeObjectForKey:(RLMKeyType)key;
  144. /**
  145. Adds a given key-value pair to the dictionary if the key is not present, or updates the value for the given key
  146. if the key already present.
  147. @warning This method may only be called during a write transaction.
  148. */
  149. - (void)setObject:(nullable RLMObjectType)obj forKeyedSubscript:(RLMKeyType)key;
  150. /**
  151. Adds a given key-value pair to the dictionary if the key is not present, or updates the value for the given key
  152. if the key already present.
  153. @warning This method may only be called during a write transaction.
  154. */
  155. - (void)setObject:(nullable RLMObjectType)anObject forKey:(RLMKeyType)aKey;
  156. /**
  157. Adds to the receiving dictionary the entries from another dictionary.
  158. @note If the receiving dictionary contains the same key(s) as the otherDictionary, then
  159. the receiving dictionary will update each key-value pair for the matching key.
  160. @warning This method may only be called during a write transaction.
  161. @param otherDictionary An enumerable object such as `NSDictionary` or `RLMDictionary` which contains objects of the
  162. same type as the receiving dictionary.
  163. */
  164. - (void)addEntriesFromDictionary:(id <NSFastEnumeration>)otherDictionary;
  165. #pragma mark - Querying a Dictionary
  166. /**
  167. Returns all the values matching the given predicate in the dictionary.
  168. @note The keys in the dictionary are ignored when quering values, and they will not be returned in the `RLMResults`.
  169. @param predicateFormat A predicate format string, optionally followed by a variable number of arguments.
  170. @return An `RLMResults` of objects that match the given predicate.
  171. */
  172. - (RLMResults<RLMObjectType> *)objectsWhere:(NSString *)predicateFormat, ...;
  173. /// :nodoc:
  174. - (RLMResults<RLMObjectType> *)objectsWhere:(NSString *)predicateFormat args:(va_list)args;
  175. /**
  176. Returns all the values matching the given predicate in the dictionary.
  177. @note The keys in the dictionary are ignored when quering values, and they will not be returned in the `RLMResults`.
  178. @param predicate The predicate with which to filter the objects.
  179. @return An `RLMResults` of objects that match the given predicate
  180. */
  181. - (RLMResults<RLMObjectType> *)objectsWithPredicate:(NSPredicate *)predicate;
  182. /**
  183. Returns a sorted RLMResults of all values in the dictionary.
  184. @note The keys in the dictionary are ignored when sorting values, and they will not be returned in the `RLMResults`.
  185. @param keyPath The key path to sort by.
  186. @param ascending The direction to sort in.
  187. @return An `RLMResults` sorted by the specified key path.
  188. */- (RLMResults<RLMObjectType> *)sortedResultsUsingKeyPath:(NSString *)keyPath ascending:(BOOL)ascending;
  189. /**
  190. Returns a sorted RLMResults of all values in the dictionary.
  191. @note The keys in the dictionary are ignored when sorting values, and they will not be returned in the `RLMResults`.
  192. @param properties An array of `RLMSortDescriptor`s to sort by.
  193. @return An `RLMResults` sorted by the specified properties.
  194. */
  195. - (RLMResults<RLMObjectType> *)sortedResultsUsingDescriptors:(NSArray<RLMSortDescriptor *> *)properties;
  196. /**
  197. Returns a distinct `RLMResults` from all values in the dictionary.
  198. @note The keys in the dictionary are ignored, and they will not be returned in the `RLMResults`.
  199. @param keyPaths The key paths to distinct on.
  200. @return An `RLMResults` with the distinct values of the keypath(s).
  201. */
  202. - (RLMResults<RLMObjectType> *)distinctResultsUsingKeyPaths:(NSArray<NSString *> *)keyPaths;
  203. #pragma mark - Aggregating Property Values
  204. /**
  205. Returns the minimum (lowest) value of the given property among all the values in the dictionary.
  206. NSNumber *min = [object.dictionaryProperty minOfProperty:@"age"];
  207. @param property The property whose minimum value is desired. Only properties of
  208. types `int`, `float`, `double`, `NSDate`, `RLMValue` and `RLMDecimal128` are supported.
  209. @return The minimum value of the property, or `nil` if the dictionary is empty.
  210. */
  211. - (nullable id)minOfProperty:(NSString *)property;
  212. /**
  213. Returns the maximum (highest) value of the given property among all the objects in the dictionary.
  214. NSNumber *max = [object.dictionaryProperty maxOfProperty:@"age"];
  215. @param property The property whose minimum value is desired. Only properties of
  216. types `int`, `float`, `double`, `NSDate`, `RLMValue` and `RLMDecimal128` are supported.
  217. @return The maximum value of the property, or `nil` if the dictionary is empty.
  218. */
  219. - (nullable id)maxOfProperty:(NSString *)property;
  220. /**
  221. Returns the sum of distinct values of a given property over all the objects in the dictionary.
  222. NSNumber *sum = [object.dictionaryProperty sumOfProperty:@"age"];
  223. @param property The property whose minimum value is desired. Only properties of
  224. types `int`, `float`, `double`, `RLMValue` and `RLMDecimal128` are supported.
  225. @return The sum of the given property.
  226. */
  227. - (NSNumber *)sumOfProperty:(NSString *)property;
  228. /**
  229. Returns the average value of a given property over the objects in the dictionary.
  230. NSNumber *average = [object.dictionaryProperty averageOfProperty:@"age"];
  231. @param property The property whose minimum value is desired. Only properties of
  232. types `int`, `float`, `double`, `NSDate`, `RLMValue` and `RLMDecimal128` are supported.
  233. @return The average value of the given property, or `nil` if the dictionary is empty.
  234. */
  235. - (nullable NSNumber *)averageOfProperty:(NSString *)property;
  236. #pragma mark - Notifications
  237. /**
  238. Registers a block to be called each time the dictionary changes.
  239. The block will be asynchronously called with the initial dictionary, and then
  240. called again after each write transaction which changes any of the keys or values
  241. within the dictionary.
  242. The `changes` parameter will be `nil` the first time the block is called.
  243. For each call after that, it will contain information about
  244. which keys in the dictionary were added, modified or deleted. If a write transaction
  245. did not modify any keys or values in the dictionary, the block is not called at all.
  246. The error parameter is present only for backwards compatibility and will always
  247. be `nil`.
  248. Notifications are delivered via the standard run loop, and so can't be
  249. delivered while the run loop is blocked by other activity. When
  250. notifications can't be delivered instantly, multiple notifications may be
  251. coalesced into a single notification. This can include the notification
  252. with the initial results. For example, the following code performs a write
  253. transaction immediately after adding the notification block, so there is no
  254. opportunity for the initial notification to be delivered first. As a
  255. result, the initial notification will reflect the state of the Realm after
  256. the write transaction.
  257. Person *person = [[Person allObjectsInRealm:realm] firstObject];
  258. NSLog(@"person.dogs.count: %zu", person.dogs.count); // => 0
  259. self.token = [person.dogs addNotificationBlock(RLMDictionary<NSString *, Dog *><RLMString, Dog> *dogs,
  260. RLMDictionaryChange *changes,
  261. NSError *error) {
  262. // Only fired once for the example
  263. NSLog(@"dogs.count: %zu", dogs.count); // => 1
  264. }];
  265. [realm transactionWithBlock:^{
  266. Dog *dog = [[Dog alloc] init];
  267. dog.name = @"Rex";
  268. person.dogs[@"frenchBulldog"] = dog;
  269. }];
  270. // end of run loop execution context
  271. You must retain the returned token for as long as you want updates to continue
  272. to be sent to the block. To stop receiving updates, call `-invalidate` on the token.
  273. @warning This method cannot be called during a write transaction, or when the
  274. containing Realm is read-only.
  275. @warning This method may only be called on a non-frozen managed dictionary.
  276. @param block The block to be called each time the dictionary changes.
  277. @return A token which must be held for as long as you want updates to be delivered.
  278. */
  279. - (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMDictionary<RLMKeyType, RLMObjectType> *_Nullable dictionary,
  280. RLMDictionaryChange *_Nullable changes,
  281. NSError *_Nullable error))block
  282. __attribute__((warn_unused_result));
  283. /**
  284. Registers a block to be called each time the dictionary changes.
  285. The block will be asynchronously called with the initial dictionary, and then
  286. called again after each write transaction which changes any of the key-value in
  287. the dictionary or which objects are in the results.
  288. The `changes` parameter will be `nil` the first time the block is called.
  289. For each call after that, it will contain information about
  290. which keys in the dictionary were added or modified. If a write transaction
  291. did not modify any objects in the dictionary, the block is not called at all.
  292. The error parameter is present only for backwards compatibility and will always
  293. be `nil`.
  294. Notifications are delivered on the given queue. If the queue is blocked and
  295. notifications can't be delivered instantly, multiple notifications may be
  296. coalesced into a single notification.
  297. You must retain the returned token for as long as you want updates to continue
  298. to be sent to the block. To stop receiving updates, call `-invalidate` on the token.
  299. @warning This method cannot be called when the containing Realm is read-only or frozen.
  300. @warning The queue must be a serial queue.
  301. @param block The block to be called whenever a change occurs.
  302. @param queue The serial queue to deliver notifications to.
  303. @return A token which must be held for as long as you want updates to be delivered.
  304. */
  305. - (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMDictionary<RLMKeyType, RLMObjectType> *_Nullable dictionary,
  306. RLMDictionaryChange *_Nullable changes,
  307. NSError *_Nullable error))block
  308. queue:(nullable dispatch_queue_t)queue
  309. __attribute__((warn_unused_result));
  310. /**
  311. Registers a block to be called each time the dictionary changes.
  312. The block will be asynchronously called with the initial dictionary, and then
  313. called again after each write transaction which changes any of the key-value in
  314. the dictionary or which objects are in the results.
  315. The `changes` parameter will be `nil` the first time the block is called.
  316. For each call after that, it will contain information about
  317. which keys in the dictionary were added or modified. If a write transaction
  318. did not modify any objects in the dictionary, the block is not called at all.
  319. The error parameter is present only for backwards compatibility and will always
  320. be `nil`.
  321. Notifications are delivered on the given queue. If the queue is blocked and
  322. notifications can't be delivered instantly, multiple notifications may be
  323. coalesced into a single notification.
  324. You must retain the returned token for as long as you want updates to continue
  325. to be sent to the block. To stop receiving updates, call `-invalidate` on the token.
  326. @warning This method cannot be called when the containing Realm is read-only or frozen.
  327. @warning The queue must be a serial queue.
  328. @param block The block to be called whenever a change occurs.
  329. @param keyPaths The block will be called for changes occurring on these keypaths. If no
  330. key paths are given, notifications are delivered for every property key path.
  331. @return A token which must be held for as long as you want updates to be delivered.
  332. */
  333. - (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMDictionary<RLMKeyType, RLMObjectType> *_Nullable dictionary,
  334. RLMDictionaryChange *_Nullable changes,
  335. NSError *_Nullable error))block
  336. keyPaths:(nullable NSArray<NSString *> *)keyPaths
  337. queue:(nullable dispatch_queue_t)queue
  338. __attribute__((warn_unused_result));
  339. /**
  340. Registers a block to be called each time the dictionary changes.
  341. The block will be asynchronously called with the initial dictionary, and then
  342. called again after each write transaction which changes any of the key-value in
  343. the dictionary or which objects are in the results.
  344. The `changes` parameter will be `nil` the first time the block is called.
  345. For each call after that, it will contain information about
  346. which keys in the dictionary were added or modified. If a write transaction
  347. did not modify any objects in the dictionary, the block is not called at all.
  348. The error parameter is present only for backwards compatibility and will always
  349. be `nil`.
  350. You must retain the returned token for as long as you want updates to continue
  351. to be sent to the block. To stop receiving updates, call `-invalidate` on the token.
  352. @warning This method cannot be called when the containing Realm is read-only or frozen.
  353. @warning The queue must be a serial queue.
  354. @param block The block to be called whenever a change occurs.
  355. @param keyPaths The block will be called for changes occurring on these keypaths. If no
  356. key paths are given, notifications are delivered for every property key path.
  357. @return A token which must be held for as long as you want updates to be delivered.
  358. */
  359. - (RLMNotificationToken *)addNotificationBlock:(void (^)(RLMDictionary<RLMKeyType, RLMObjectType> *_Nullable dictionary,
  360. RLMDictionaryChange *_Nullable changes,
  361. NSError *_Nullable error))block
  362. keyPaths:(nullable NSArray<NSString *> *)keyPaths
  363. __attribute__((warn_unused_result));
  364. #pragma mark - Freeze
  365. /**
  366. Returns a frozen (immutable) snapshot of a dictionary.
  367. The frozen copy is an immutable dictionary which contains the same data as this
  368. dictionary currently contains, but will not update when writes are made to the
  369. containing Realm. Unlike live dictionaries, frozen dictionaries can be accessed from any
  370. thread.
  371. @warning This method cannot be called during a write transaction, or when the
  372. containing Realm is read-only.
  373. @warning This method may only be called on a managed dictionary.
  374. @warning Holding onto a frozen dictionary for an extended period while performing
  375. write transaction on the Realm may result in the Realm file growing
  376. to large sizes. See `RLMRealmConfiguration.maximumNumberOfActiveVersions`
  377. for more information.
  378. */
  379. - (instancetype)freeze;
  380. /**
  381. Returns a live version of this frozen collection.
  382. This method resolves a reference to a live copy of the same frozen collection.
  383. If called on a live collection, will return itself.
  384. */
  385. - (instancetype)thaw;
  386. #pragma mark - Unavailable Methods
  387. /**
  388. `-[RLMDictionary init]` is not available because `RLMDictionary`s cannot be created directly.
  389. `RLMDictionary` properties on `RLMObject`s are lazily created when accessed.
  390. */
  391. - (instancetype)init __attribute__((unavailable("RLMDictionary cannot be created directly")));
  392. /**
  393. `+[RLMDictionary new]` is not available because `RLMDictionary`s cannot be created directly.
  394. `RLMDictionary` properties on `RLMObject`s are lazily created when accessed.
  395. */
  396. + (instancetype)new __attribute__((unavailable("RLMDictionary cannot be created directly")));
  397. @end
  398. /**
  399. A `RLMDictionaryChange` object encapsulates information about changes to dictionaries
  400. that are reported by Realm notifications.
  401. `RLMDictionaryChange` is passed to the notification blocks registered with
  402. `-addNotificationBlock` on `RLMDictionary`, and reports what keys in the
  403. dictionary changed since the last time the notification block was called.
  404. */
  405. @interface RLMDictionaryChange : NSObject
  406. /// The keys in the new version of the dictionary which were newly inserted.
  407. @property (nonatomic, readonly) NSArray<id> *insertions;
  408. /// The keys in the new version of the dictionary which were modified.
  409. @property (nonatomic, readonly) NSArray<id> *modifications;
  410. /// The keys which were deleted from the old version.
  411. @property (nonatomic, readonly) NSArray<id> *deletions;
  412. @end
  413. RLM_HEADER_AUDIT_END(nullability, sendability)