├── Helpers ├── RLMObject+Notifications.h ├── RLMObject+Notifications.m ├── RLMRealm+Notifications.h ├── RLMRealm+Notifications.m ├── RLMResults+Notifications.h └── RLMResults+Notifications.m ├── LICENSE ├── RBQRealmNotificationManager.h ├── RBQRealmNotificationManager.m └── README.md /Helpers/RLMObject+Notifications.h: -------------------------------------------------------------------------------- 1 | // 2 | // RLMObject+Notifications.h 3 | // RBQFetchedResultsControllerExample 4 | // 5 | // Created by Adam Fish on 1/13/15. 6 | // Copyright (c) 2015 Roobiq. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | /** 12 | Block used to edit a RLMObject while automatically notifying RBQRealmChangeLogger 13 | 14 | @param object Object to be edited (will need to be cast into appropriate subclass) 15 | */ 16 | NS_ASSUME_NONNULL_BEGIN 17 | typedef void(^RBQChangeNotificationBlock)(id object); 18 | NS_ASSUME_NONNULL_END 19 | 20 | /** 21 | * Category on RLMObject that provides convenience methods to change a RLMObject while automatically notifying RBQRealmChangeLogger 22 | */ 23 | @interface RLMObject (Notifications) 24 | 25 | /** 26 | * Convenience method that accepts a RBQChangeNotificationBlock, which contains the current RLMObject as a parameter. 27 | * 28 | * Edit the parameter object in the block and an automatic notification will be generated for RBQRealmChangeLogger 29 | * 30 | * @param block Block contains the RLMObject used to call this method. Edit the RLMObject within the block. 31 | */ 32 | - (void)changeWithNotification:(nonnull RBQChangeNotificationBlock)block; 33 | 34 | /** 35 | * Convenience method that accepts a RBQChangeNotificationBlock, which contains the current RLMObject as a parameter. 36 | * 37 | * The block will be run within the required beginWriteTransaction and commitWriteTransaction calls automatically. Edit the parameter object in the block and an automatic notification will be generated for RBQRealmChangeLogger. 38 | * 39 | * @param block Block contains the RLMObject used to call this method. Edit the RLMObject within the block. 40 | */ 41 | - (void)changeWithNotificationInTransaction:(nonnull RBQChangeNotificationBlock)block; 42 | 43 | @end 44 | -------------------------------------------------------------------------------- /Helpers/RLMObject+Notifications.m: -------------------------------------------------------------------------------- 1 | // 2 | // RLMObject+Notifications.m 3 | // RBQFetchedResultsControllerExample 4 | // 5 | // Created by Adam Fish on 1/13/15. 6 | // Copyright (c) 2015 Roobiq. All rights reserved. 7 | // 8 | 9 | #import "RLMObject+Notifications.h" 10 | #import "RBQRealmNotificationManager.h" 11 | 12 | @implementation RLMObject (Notifications) 13 | 14 | - (void)changeWithNotification:(RBQChangeNotificationBlock)block 15 | { 16 | block(self); 17 | 18 | // Call Notification 19 | [[RBQRealmChangeLogger loggerForRealm:self.realm] didChangeObject:self]; 20 | } 21 | 22 | - (void)changeWithNotificationInTransaction:(RBQChangeNotificationBlock)block 23 | { 24 | RLMRealm *realm = self.realm; 25 | 26 | [realm beginWriteTransaction]; 27 | 28 | block(self); 29 | 30 | // Call Notification 31 | [[RBQRealmChangeLogger loggerForRealm:self.realm] didChangeObject:self]; 32 | 33 | [realm commitWriteTransaction]; 34 | } 35 | 36 | @end 37 | -------------------------------------------------------------------------------- /Helpers/RLMRealm+Notifications.h: -------------------------------------------------------------------------------- 1 | // 2 | // RLMRealm+Notifications.h 3 | // RBQFetchedResultsControllerExample 4 | // 5 | // Created by Adam Fish on 1/13/15. 6 | // Copyright (c) 2015 Roobiq. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | /** 12 | * Category on RLMRealm that provides convenience methods similar to RLMRealm class methods but include notifying RBQRealmNotificationManager 13 | */ 14 | @interface RLMRealm (Notifications) 15 | 16 | /** 17 | * Convenience method to add an object to the Realm and notify RBQRealmChangeLogger 18 | * 19 | * @param object Standalone RLMObject to be persisted 20 | */ 21 | - (void)addObjectWithNotification:(nonnull RLMObject *)object; 22 | 23 | /** 24 | * Convenience method to add a collection of RLMObjects to the Realm and notify RBQRealmChangeLogger 25 | * 26 | * @param array A collection object that conforms to NSFastEnumeration (e.g. NSArray, RLMArray, RLMResults) 27 | */ 28 | - (void)addObjectsWithNotification:(nonnull id)array; 29 | 30 | /** 31 | * Convenience method to add or update a RLMObject to the Realm and notify RBQRealmChangeLogger 32 | * 33 | * If the RLMObject is already persisted, then the new object will be used to update the persisted object. 34 | * 35 | * @param object RLMObject to add or update in the Realm 36 | */ 37 | - (void)addOrUpdateObjectWithNotification:(nonnull RLMObject *)object; 38 | 39 | /** 40 | * Convenience method to add or update a collection of RLMObjects to the Realm and notify RBQRealmChangeLogger 41 | * 42 | * If any RLMObject is already persisted, then the new object will be used to update the persisted object. 43 | * 44 | * @param array A collection object that conforms to NSFastEnumeration (e.g. NSArray, RLMArray, RLMResults) 45 | */ 46 | - (void)addOrUpdateObjectsFromArrayWithNotification:(nonnull id)array; 47 | 48 | /** 49 | * Convenience method to delete a RLMObject from the Realm and notify RBQRealmChangeLogger 50 | * 51 | * @param object RLMObject to delete from the Realm 52 | */ 53 | - (void)deleteObjectWithNotification:(nonnull RLMObject *)object; 54 | 55 | /** 56 | * Convenience method to delete a collection of RLMObjects from the Realm and notify RBQRealmChangeLogger 57 | * 58 | * @param array A collection object that conforms to NSFastEnumeration (e.g. NSArray, RLMArray, RLMResults) 59 | */ 60 | - (void)deleteObjectsWithNotification:(nonnull id)array; 61 | 62 | @end 63 | -------------------------------------------------------------------------------- /Helpers/RLMRealm+Notifications.m: -------------------------------------------------------------------------------- 1 | // 2 | // RLMRealm+Notifications.m 3 | // RBQFetchedResultsControllerExample 4 | // 5 | // Created by Adam Fish on 1/13/15. 6 | // Copyright (c) 2015 Roobiq. All rights reserved. 7 | // 8 | 9 | #import "RLMRealm+Notifications.h" 10 | #import "RLMObject+Utilities.h" 11 | #import "RBQRealmNotificationManager.h" 12 | 13 | @implementation RLMRealm (Notifications) 14 | 15 | - (void)addObjectWithNotification:(RLMObject *)object 16 | { 17 | [self addObject:object]; 18 | 19 | [[RBQRealmChangeLogger loggerForRealm:self] didAddObject:object]; 20 | } 21 | 22 | - (void)addObjectsWithNotification:(id)array 23 | { 24 | for (RLMObject *object in array) { 25 | if (![object isKindOfClass:[RLMObject class]]) { 26 | NSString *msg = [NSString stringWithFormat:@"Cannot insert objects of type %@ with addObjects:. Only RLMObjects are supported.", NSStringFromClass(object.class)]; 27 | @throw [NSException exceptionWithName:@"RLMException" reason:msg userInfo:nil]; 28 | } 29 | 30 | [self addObjectWithNotification:object]; 31 | } 32 | } 33 | 34 | - (void)addOrUpdateObjectWithNotification:(RLMObject *)object 35 | { 36 | BOOL isAddition = NO; 37 | 38 | if (object.realm != self && ![object isContainedInRealm:self]) { 39 | isAddition = YES; 40 | } 41 | 42 | [self addOrUpdateObject:object]; 43 | 44 | if (isAddition) { 45 | [[RBQRealmChangeLogger loggerForRealm:self] didAddObject:object]; 46 | } 47 | else { 48 | [[RBQRealmChangeLogger loggerForRealm:self] didChangeObject:object]; 49 | } 50 | } 51 | 52 | - (void)addOrUpdateObjectsFromArrayWithNotification:(id)array 53 | { 54 | for (RLMObject *object in array) { 55 | [self addOrUpdateObjectWithNotification:object]; 56 | } 57 | } 58 | 59 | - (void)deleteObjectWithNotification:(RLMObject *)object 60 | { 61 | [[RBQRealmChangeLogger loggerForRealm:self] willDeleteObject:object]; 62 | 63 | [self deleteObject:object]; 64 | } 65 | 66 | - (void)deleteObjectsWithNotification:(id)array 67 | { 68 | for (RLMObject *object in array) { 69 | [[RBQRealmChangeLogger loggerForRealm:self] willDeleteObject:object]; 70 | } 71 | 72 | [self deleteObjects:array]; 73 | } 74 | 75 | @end 76 | -------------------------------------------------------------------------------- /Helpers/RLMResults+Notifications.h: -------------------------------------------------------------------------------- 1 | // 2 | // RLMResults+Notifications.h 3 | // RBQFRCDynamicExample 4 | // 5 | // Created by Adam Fish on 7/23/15. 6 | // Copyright (c) 2015 Adam Fish. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | /** 12 | * Helper category for RLMResults that supports registering changes when performing bulk updates. 13 | */ 14 | @interface RLMResults (Notifications) 15 | 16 | /** 17 | * Bulk update values by invoking `setValue:forKey:` and registers a change 18 | * on each of the array's items using the specified `value` and `key`. 19 | * 20 | * @param value The object value. 21 | * @param key The name of the property. 22 | */ 23 | - (void)setValueWithNotification:(nonnull id)value forKey:(nonnull NSString *)key; 24 | 25 | @end 26 | -------------------------------------------------------------------------------- /Helpers/RLMResults+Notifications.m: -------------------------------------------------------------------------------- 1 | // 2 | // RLMResults+Notifications.m 3 | // RBQFRCDynamicExample 4 | // 5 | // Created by Adam Fish on 7/23/15. 6 | // Copyright (c) 2015 Adam Fish. All rights reserved. 7 | // 8 | 9 | #import "RLMResults+Notifications.h" 10 | #import "RBQRealmNotificationManager.h" 11 | 12 | @implementation RLMResults (Notifications) 13 | 14 | - (void)setValueWithNotification:(id)value forKey:(NSString *)key 15 | { 16 | // Perform the changes 17 | [self setValue:value forKey:key]; 18 | 19 | // Register Notifications 20 | [[RBQRealmChangeLogger loggerForRealm:self.realm] didChangeObjects:self]; 21 | } 22 | 23 | @end 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /RBQRealmNotificationManager.h: -------------------------------------------------------------------------------- 1 | // 2 | // RBQRealmNotificationManager.h 3 | // RBQRealmNotificationManage 4 | // 5 | // Created by Adam Fish on 1/4/15. 6 | // Copyright (c) 2015 Roobiq. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | @class RBQSafeRealmObject; 13 | 14 | #pragma mark - RBQClassChangesObject 15 | 16 | /** 17 | * Class used by the RBQRealmNotificationManager to represent the change set for a given entity. This object is passed in the NSDictionary (keyed by the entity name) contained in the RBQNotificationBlock after a change to monitored Realm. 18 | */ 19 | @interface RBQEntityChangesObject : NSObject 20 | 21 | /** 22 | * The class name of the entity 23 | */ 24 | @property (readonly, nonatomic, nonnull) NSString *className; 25 | 26 | /** 27 | * Collection of RBQSafeRealmObjects representing the added objects 28 | */ 29 | @property (readonly, nonatomic, nonnull) NSSet *addedSafeObjects; 30 | 31 | /** 32 | * Collection of RBQSafeRealmObjects representing the deleted objects 33 | */ 34 | @property (readonly, nonatomic, nonnull) NSSet *deletedSafeObjects; 35 | 36 | /** 37 | * Collection of RBQSafeRealmObjects representing the changed objects 38 | */ 39 | @property (readonly, nonatomic, nonnull) NSSet *changedSafeObjects; 40 | 41 | + (nonnull instancetype)createEntityChangeObjectWithClassName:(nonnull NSString *)className; 42 | 43 | - (void)didAddSafeObject:(nonnull RBQSafeRealmObject *)safeObject; 44 | 45 | - (void)willDeleteSafeObject:(nonnull RBQSafeRealmObject *)safeObject; 46 | 47 | - (void)didChangeSafeObject:(nonnull RBQSafeRealmObject *)safeObject; 48 | 49 | @end 50 | 51 | #pragma mark - Constants 52 | 53 | /** 54 | * When added to a RBQRealmNotificationManager, this block fires when the tracked Realm changes. 55 | * 56 | * @param entityChanges NSDictionary with the keys represented as the class name of an entity that had changes. The object in the dictionary is a RBQEntityChangesObject, which contains the specific changes. 57 | * @param realm RLMRealm that updated (this is the original RLMRealm instance that was acted on to perform the changes. Not thread-safe). 58 | */ 59 | NS_ASSUME_NONNULL_BEGIN 60 | typedef void(^RBQNotificationBlock)(NSDictionary *entityChanges, 61 | RLMRealm *realm); 62 | NS_ASSUME_NONNULL_END 63 | 64 | @interface RBQNotificationToken : NSObject 65 | 66 | @end 67 | 68 | /** 69 | * This class is used to track changes to a given RLMRealm. Since Realm doesn't support automatic change tracking, this class allows the developer to log object changes, which will be passed along to the RBQRealmNotificationManager who in turn broadcasts it to any listeners 70 | * 71 | * Since RLMObjects are not thread-safe, when an object is logged to the manager, it is internally transformed into an RBQSafeRealmObject that is thread-safe and this will then be passed to any listeners once the Realm being monitored updates. 72 | * 73 | * @warning Only RLMObjects with primary keys can be logged because the primary key is required to create a RBQSafeRealmObject. 74 | */ 75 | @interface RBQRealmChangeLogger : NSObject 76 | 77 | @property (readonly, nonatomic, nonnull) NSDictionary *entityChanges; 78 | 79 | /** 80 | * Creates or retrieves the logger instance for the default Realm on the current thread 81 | * 82 | * @return Instance of RBQRealmChangeLogger 83 | */ 84 | + (nonnull instancetype)defaultLogger; 85 | 86 | /** 87 | * Creates or retrieves the logger instance for a specific Realm on the current thread 88 | * 89 | * @param realm A RLMRealm instance 90 | * 91 | * @return Instance of RBQRealmChangeLogger 92 | */ 93 | + (nonnull instancetype)loggerForRealm:(nonnull RLMRealm *)realm; 94 | 95 | /** 96 | * Register an addition for a given RLMObject 97 | * 98 | * @warning Can be called before or after the addition to Realm 99 | * 100 | * @param addedObject Added RLMObject 101 | */ 102 | - (void)didAddObject:(nonnull RLMObjectBase *)addedObject; 103 | 104 | /** 105 | * Register a collection of RLMObject additions 106 | * 107 | * @warning Can be called before or after the additions to Realm 108 | * 109 | * @param addedObjects RLMArray, RLMResults, NSSet, or NSArray of added RLMObjects 110 | */ 111 | - (void)didAddObjects:(nonnull id)addedObjects; 112 | 113 | /** 114 | * Register a delete for a given RLMObject 115 | * 116 | * @warning Must be called before the delete in Realm (since the RLMObject will then be invalidated). 117 | * 118 | * @param deletedObject To be deleted RLMObject 119 | */ 120 | - (void)willDeleteObject:(nonnull RLMObjectBase *)deletedObject; 121 | 122 | /** 123 | * Register a collection of RLMObject deletes 124 | * 125 | * @warning Must be called before the delete in Realm (since the RLMObject will then be invalidated). 126 | * 127 | * @param deletedObjects RLMArray, RLMResults, NSSet, or NSArray of deleted RLMObjects 128 | */ 129 | - (void)willDeleteObjects:(nonnull id)deletedObjects; 130 | 131 | /** 132 | * Register a change for a given RLMObject 133 | * 134 | * @warning Can be called before or after change to Realm 135 | * 136 | * @param changedObject Changed RLMObject 137 | */ 138 | - (void)didChangeObject:(nonnull RLMObjectBase *)changedObject; 139 | 140 | /** 141 | * Register a collection of RLMObject changes 142 | * 143 | * @warning Can be called before or after change to Realm 144 | * 145 | * @param changedObjects RLMArray, RLMResults, NSSet, or NSArray of changed RLMObjects 146 | */ 147 | - (void)didChangeObjects:(nonnull id)changedObjects; 148 | 149 | /** 150 | * Convenience method to pass array of objects changed. Will ignore nil values; 151 | * 152 | * @param addedObjects RLMArray, RLMResults, NSSet, or NSArray of added RLMObjects 153 | * @param deletedObjects RLMArray, RLMResults, NSSet, or NSArray of deleted RLMObjects 154 | * @param changedObjects RLMArray, RLMResults, NSSet, or NSArray of changed RLMObjects 155 | */ 156 | - (void)didAddObjects:(nonnull id)addedObjects 157 | willDeleteObjects:(nonnull id)deletedObjects 158 | didChangeObjects:(nonnull id)changedObjects; 159 | 160 | @end 161 | 162 | /** 163 | * This class works in conjunction with any instances of RBQRealmChangeLogger to broadcast any changes to the registered listeners 164 | */ 165 | @interface RBQRealmNotificationManager : NSObject 166 | 167 | /** 168 | * Retrieve the singleton RBQRealmNotificationManager that passes changes from all Realm loggers 169 | * 170 | * @return Singleton RBQRealmNotificationManager 171 | */ 172 | + (nonnull instancetype)defaultManager; 173 | 174 | /** 175 | * Use this method to add a notification block that will fire every time the Realm for this RBQNotificationManager updates. The block passes the changes from the Realm update that were logged to the RBQRealmNotificationManager. 176 | * 177 | * @param block RBQNotificationBlock that passes a NSDictionary keyed by entity name. The object for the key is a RBQEntityChangesObject which contains NSSets of all the various changes to the entity. 178 | * 179 | * @warning You must hold onto a strong reference to the returned token or it will be deallocated, preventing any changes from propogating. 180 | * 181 | * @see RBQEntityChangesObject 182 | * @see RBQNotificationBlock 183 | * 184 | * @return A new instance of RBQNotificationToken. 185 | */ 186 | - (nonnull RBQNotificationToken *)addNotificationBlock:(nonnull RBQNotificationBlock)block; 187 | 188 | /** 189 | * De-register a notification given a RBQNotificationToken. 190 | * 191 | * @param token The RBQNotificationToken to be de-registered. 192 | */ 193 | - (void)removeNotification:(nonnull RBQNotificationToken *)token; 194 | 195 | @end 196 | -------------------------------------------------------------------------------- /RBQRealmNotificationManager.m: -------------------------------------------------------------------------------- 1 | // 2 | // RBQRealmNotificationManager.m 3 | // RBQRealmNotificationManage 4 | // 5 | // Created by Adam Fish on 1/4/15. 6 | // Copyright (c) 2015 Roobiq. All rights reserved. 7 | // 8 | 9 | #import "RBQRealmNotificationManager.h" 10 | #import "RBQSafeRealmObject.h" 11 | 12 | #include 13 | #import 14 | 15 | #pragma mark - RBQEntityChangesObject 16 | 17 | @interface RBQEntityChangesObject () 18 | 19 | @property (strong, nonatomic) NSMutableSet *internalAddedSafeObjects; 20 | @property (strong, nonatomic) NSMutableSet *internalDeletedSafeObjects; 21 | @property (strong, nonatomic) NSMutableSet *internalChangedSafeObjects; 22 | 23 | + (instancetype)createEntityChangeObjectWithClassName:(NSString *)className; 24 | 25 | - (void)didAddSafeObject:(RBQSafeRealmObject *)safeObject; 26 | - (void)willDeleteSafeObject:(RBQSafeRealmObject *)safeObject; 27 | - (void)didChangeSafeObject:(RBQSafeRealmObject *)safeObject; 28 | 29 | @end 30 | 31 | @implementation RBQEntityChangesObject 32 | @synthesize className = _className; 33 | 34 | + (instancetype)createEntityChangeObjectWithClassName:(NSString *)className 35 | { 36 | RBQEntityChangesObject *changeObject = [[RBQEntityChangesObject alloc] init]; 37 | changeObject->_className = className; 38 | changeObject.internalAddedSafeObjects = [[NSMutableSet alloc] init]; 39 | changeObject.internalDeletedSafeObjects = [[NSMutableSet alloc] init]; 40 | changeObject.internalChangedSafeObjects = [[NSMutableSet alloc] init]; 41 | 42 | return changeObject; 43 | } 44 | 45 | - (void)didAddSafeObject:(RBQSafeRealmObject *)safeObject 46 | { 47 | @synchronized(self.internalAddedSafeObjects) { 48 | [self.internalAddedSafeObjects addObject:safeObject]; 49 | } 50 | } 51 | 52 | - (void)willDeleteSafeObject:(RBQSafeRealmObject *)safeObject 53 | { 54 | @synchronized(self.internalDeletedSafeObjects) { 55 | [self.internalDeletedSafeObjects addObject:safeObject]; 56 | } 57 | } 58 | 59 | - (void)didChangeSafeObject:(RBQSafeRealmObject *)safeObject 60 | { 61 | @synchronized(self.internalChangedSafeObjects) { 62 | [self.internalChangedSafeObjects addObject:safeObject]; 63 | } 64 | } 65 | 66 | #pragma mark - Getters 67 | 68 | - (NSSet *)addedSafeObjects 69 | { 70 | return self.internalAddedSafeObjects.copy; 71 | } 72 | 73 | - (NSSet *)deletedSafeObjects 74 | { 75 | return self.internalDeletedSafeObjects.copy; 76 | } 77 | 78 | - (NSSet *)changedSafeObjects 79 | { 80 | return self.internalChangedSafeObjects.copy; 81 | } 82 | 83 | @end 84 | 85 | #pragma mark - RBQNotificationToken 86 | 87 | @interface RBQNotificationToken () 88 | 89 | @property (nonatomic, copy) RBQNotificationBlock block; 90 | 91 | @end 92 | 93 | @implementation RBQNotificationToken 94 | 95 | 96 | - (void)dealloc 97 | { 98 | if (_block) { 99 | NSLog(@"RBQNotificationToken released without unregistering a notification. You must hold \ 100 | on to the RBQNotificationToken returned from addNotificationBlock and call \ 101 | removeNotification: when you no longer wish to recieve RBQRealm notifications."); 102 | } 103 | } 104 | 105 | @end 106 | 107 | #pragma mark - RBQRealmNotificationManager 108 | 109 | @interface RBQRealmNotificationManager () { 110 | NSMapTable *_notificationHandlers; 111 | } 112 | 113 | - (void)sendNotificationsWithRealm:(RLMRealm *)realm 114 | entityChanges:(NSDictionary *)entityChanges; 115 | 116 | @end 117 | 118 | @implementation RBQRealmNotificationManager 119 | 120 | #pragma mark - Class 121 | 122 | + (instancetype)defaultManager 123 | { 124 | static RBQRealmNotificationManager *_defaultManager = nil; 125 | static dispatch_once_t onceToken; 126 | dispatch_once(&onceToken, ^{ 127 | _defaultManager = [[self alloc] init]; 128 | }); 129 | return _defaultManager; 130 | } 131 | 132 | #pragma mark - Instance 133 | 134 | - (id)init 135 | { 136 | self = [super init]; 137 | 138 | if (self) { 139 | _notificationHandlers = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsWeakMemory 140 | valueOptions:NSPointerFunctionsWeakMemory]; 141 | } 142 | 143 | return self; 144 | } 145 | 146 | #pragma mark - Public Notification Methods 147 | 148 | - (RBQNotificationToken *)addNotificationBlock:(RBQNotificationBlock)block 149 | { 150 | if (!block) { 151 | @throw [NSException exceptionWithName:@"RBQException" 152 | reason:@"The notification block should not be nil" 153 | userInfo:nil]; 154 | } 155 | 156 | RBQNotificationToken *token = [[RBQNotificationToken alloc] init]; 157 | 158 | token.block = block; 159 | 160 | @synchronized(_notificationHandlers) { 161 | [_notificationHandlers setObject:token forKey:token]; 162 | } 163 | 164 | return token; 165 | } 166 | 167 | - (void)removeNotification:(RBQNotificationToken *)token 168 | { 169 | if (token) { 170 | @synchronized(_notificationHandlers) { 171 | [_notificationHandlers removeObjectForKey:token]; 172 | } 173 | 174 | token.block = nil; 175 | } 176 | } 177 | 178 | #pragma mark - RBQNotification 179 | 180 | // Calling this method will broadcast any registered changes 181 | - (void)sendNotificationsWithRealm:(RLMRealm *)realm 182 | entityChanges:(NSDictionary *)entityChanges 183 | { 184 | // call this realms notification blocks 185 | for (RBQNotificationToken *token in [_notificationHandlers copy]) { 186 | if (token.block) { 187 | 188 | token.block(entityChanges, 189 | realm); 190 | } 191 | } 192 | } 193 | 194 | @end 195 | 196 | 197 | #pragma mark - Global 198 | 199 | // Global RBQRealmNotificationManager instance cache 200 | static NSMutableDictionary *s_loggersPerPath; 201 | 202 | static RBQRealmChangeLogger *cachedRealmChangeLogger(NSString *path) { 203 | mach_port_t threadID = pthread_mach_thread_np(pthread_self()); 204 | @synchronized(s_loggersPerPath) { 205 | return [s_loggersPerPath[path] objectForKey:@(threadID)]; 206 | } 207 | } 208 | 209 | static void cacheRealmChangeLogger(RBQRealmChangeLogger *logger, NSString *path) { 210 | mach_port_t threadID = pthread_mach_thread_np(pthread_self()); 211 | @synchronized(s_loggersPerPath) { 212 | if (!s_loggersPerPath[path]) { 213 | s_loggersPerPath[path] = [NSMapTable mapTableWithKeyOptions:NSPointerFunctionsObjectPersonality 214 | valueOptions:NSPointerFunctionsWeakMemory]; 215 | } 216 | [s_loggersPerPath[path] setObject:logger forKey:@(threadID)]; 217 | } 218 | } 219 | 220 | static void clearManagerCache() { 221 | @synchronized(s_loggersPerPath) { 222 | for (NSMapTable *map in s_loggersPerPath.allValues) { 223 | [map removeAllObjects]; 224 | } 225 | s_loggersPerPath = [NSMutableDictionary dictionary]; 226 | } 227 | } 228 | 229 | #pragma mark - Constants 230 | 231 | static NSString * const kRBQAddedSafeObjectsKey = @"RBQAddedSafeObjectsKey"; 232 | static NSString * const kRBQDeletedSafeObjectsKey = @"RBQDeletedSafeObjectsKey"; 233 | static NSString * const kRBQChangedSafeObjectsKey = @"RBQChangedSafeObjectsKey"; 234 | static char kAssociatedObjectKey; 235 | 236 | #pragma mark - RBQRealmChangeLogger 237 | 238 | @interface RBQRealmChangeLogger () 239 | 240 | @property (strong, nonatomic) NSMutableDictionary *internalEntityChanges; 241 | 242 | @property (strong, nonatomic) RLMNotificationToken *token; 243 | 244 | @property (weak, nonatomic) RLMRealm *realm; 245 | 246 | @end 247 | 248 | @implementation RBQRealmChangeLogger 249 | 250 | #pragma mark - Private Class 251 | 252 | + (void)initialize 253 | { 254 | static bool initialized; 255 | if (initialized) { 256 | return; 257 | } 258 | initialized = true; 259 | 260 | clearManagerCache(); 261 | } 262 | 263 | #pragma mark - Public Class 264 | 265 | + (instancetype)defaultLogger 266 | { 267 | return [RBQRealmChangeLogger loggerForRealm:[RLMRealm defaultRealm]]; 268 | } 269 | 270 | + (instancetype)loggerForRealm:(RLMRealm *)realm 271 | { 272 | RBQRealmChangeLogger *logger = cachedRealmChangeLogger(realm.path); 273 | 274 | if (!logger) { 275 | logger = [[self alloc] init]; 276 | 277 | logger.realm = realm; 278 | 279 | [logger tokenCheck]; 280 | 281 | // Associate the logger with the realm so we get dealloc when it does 282 | objc_setAssociatedObject(realm, &kAssociatedObjectKey, logger, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 283 | 284 | // Add the manager to the cache 285 | cacheRealmChangeLogger(logger, realm.path); 286 | } 287 | 288 | return logger; 289 | } 290 | 291 | #pragma mark - Public Instance 292 | 293 | - (void)didAddObject:(RLMObjectBase *)addedObject 294 | { 295 | if (addedObject && 296 | !addedObject.invalidated) { 297 | 298 | [self tokenCheck]; 299 | 300 | // Save a safe object to use across threads 301 | RBQSafeRealmObject *safeObject = [RBQSafeRealmObject safeObjectFromObject:addedObject]; 302 | 303 | RBQEntityChangesObject *entityChangesObject = [self createOrRetrieveEntityChangesForClassName:safeObject.className]; 304 | 305 | [entityChangesObject didAddSafeObject:safeObject]; 306 | } 307 | } 308 | 309 | - (void)didAddObjects:(id)addedObjects 310 | { 311 | if (addedObjects) { 312 | 313 | [self tokenCheck]; 314 | 315 | for (RLMObjectBase *addedObject in addedObjects) { 316 | 317 | if (addedObject && 318 | !addedObject.invalidated) { 319 | 320 | // Save a safe object to use across threads 321 | RBQSafeRealmObject *safeObject = [RBQSafeRealmObject safeObjectFromObject:addedObject]; 322 | 323 | RBQEntityChangesObject *entityChangesObject = [self createOrRetrieveEntityChangesForClassName:safeObject.className]; 324 | 325 | [entityChangesObject didAddSafeObject:safeObject]; 326 | } 327 | } 328 | } 329 | } 330 | 331 | - (void)willDeleteObject:(RLMObjectBase *)deletedObject 332 | { 333 | if (deletedObject && 334 | !deletedObject.invalidated) { 335 | 336 | [self tokenCheck]; 337 | 338 | // Save a safe object to use across threads 339 | RBQSafeRealmObject *safeObject = [RBQSafeRealmObject safeObjectFromObject:deletedObject]; 340 | 341 | RBQEntityChangesObject *entityChangesObject = [self createOrRetrieveEntityChangesForClassName:safeObject.className]; 342 | 343 | [entityChangesObject willDeleteSafeObject:safeObject]; 344 | } 345 | } 346 | 347 | - (void)willDeleteObjects:(id)deletedObjects 348 | { 349 | if (deletedObjects) { 350 | 351 | [self tokenCheck]; 352 | 353 | for (RLMObjectBase *deletedObject in deletedObjects) { 354 | 355 | if (deletedObject && 356 | !deletedObject.invalidated) { 357 | 358 | // Save a safe object to use across threads 359 | RBQSafeRealmObject *safeObject = [RBQSafeRealmObject safeObjectFromObject:deletedObject]; 360 | 361 | RBQEntityChangesObject *entityChangesObject = [self createOrRetrieveEntityChangesForClassName:safeObject.className]; 362 | 363 | [entityChangesObject willDeleteSafeObject:safeObject]; 364 | } 365 | } 366 | } 367 | } 368 | 369 | - (void)didChangeObject:(RLMObjectBase *)changedObject 370 | { 371 | if (changedObject && 372 | !changedObject.invalidated) { 373 | 374 | [self tokenCheck]; 375 | 376 | // Save a safe object to use across threads 377 | RBQSafeRealmObject *safeObject = [RBQSafeRealmObject safeObjectFromObject:changedObject]; 378 | 379 | RBQEntityChangesObject *entityChangesObject = [self createOrRetrieveEntityChangesForClassName:safeObject.className]; 380 | 381 | [entityChangesObject didChangeSafeObject:safeObject]; 382 | } 383 | } 384 | 385 | - (void)didChangeObjects:(id)changedObjects 386 | { 387 | if (changedObjects) { 388 | 389 | [self tokenCheck]; 390 | 391 | for (RLMObjectBase *changedObject in changedObjects) { 392 | 393 | if (changedObject && 394 | !changedObject.invalidated) { 395 | 396 | // Save a safe object to use across threads 397 | RBQSafeRealmObject *safeObject = [RBQSafeRealmObject safeObjectFromObject:changedObject]; 398 | 399 | RBQEntityChangesObject *entityChangesObject = [self createOrRetrieveEntityChangesForClassName:safeObject.className]; 400 | 401 | [entityChangesObject didChangeSafeObject:safeObject]; 402 | } 403 | } 404 | } 405 | } 406 | 407 | - (void)didAddObjects:(id)addedObjects 408 | willDeleteObjects:(id)deletedObjects 409 | didChangeObjects:(id)changedObjects 410 | { 411 | [self tokenCheck]; 412 | 413 | if (addedObjects) { 414 | 415 | for (RLMObjectBase *addedObject in addedObjects) { 416 | 417 | if (addedObject && 418 | !addedObject.invalidated) { 419 | 420 | // Save a safe object to use across threads 421 | RBQSafeRealmObject *safeObject = [RBQSafeRealmObject safeObjectFromObject:addedObject]; 422 | 423 | RBQEntityChangesObject *entityChangesObject = [self createOrRetrieveEntityChangesForClassName:safeObject.className]; 424 | 425 | [entityChangesObject didAddSafeObject:safeObject]; 426 | } 427 | } 428 | } 429 | 430 | if (deletedObjects) { 431 | 432 | for (RLMObjectBase *deletedObject in deletedObjects) { 433 | 434 | if (deletedObject && 435 | !deletedObject.invalidated) { 436 | 437 | // Save a safe object to use across threads 438 | RBQSafeRealmObject *safeObject = [RBQSafeRealmObject safeObjectFromObject:deletedObject]; 439 | 440 | RBQEntityChangesObject *entityChangesObject = [self createOrRetrieveEntityChangesForClassName:safeObject.className]; 441 | 442 | [entityChangesObject willDeleteSafeObject:safeObject]; 443 | } 444 | } 445 | } 446 | 447 | if (changedObjects) { 448 | 449 | for (RLMObjectBase *changedObject in changedObjects) { 450 | 451 | if (changedObject && 452 | !changedObject.invalidated) { 453 | 454 | // Save a safe object to use across threads 455 | RBQSafeRealmObject *safeObject = [RBQSafeRealmObject safeObjectFromObject:changedObject]; 456 | 457 | RBQEntityChangesObject *entityChangesObject = [self createOrRetrieveEntityChangesForClassName:safeObject.className]; 458 | 459 | [entityChangesObject didChangeSafeObject:safeObject]; 460 | } 461 | } 462 | } 463 | } 464 | 465 | #pragma mark - Getters 466 | 467 | - (NSDictionary *)entityChanges 468 | { 469 | @synchronized(self.internalEntityChanges) { 470 | return self.internalEntityChanges.copy; 471 | } 472 | } 473 | 474 | - (NSMutableDictionary *)internalEntityChanges 475 | { 476 | if (!_internalEntityChanges) { 477 | _internalEntityChanges = @{}.mutableCopy; 478 | } 479 | 480 | return _internalEntityChanges; 481 | } 482 | 483 | #pragma mark - RLMNotification 484 | 485 | - (void)registerChangeNotification 486 | { 487 | typeof(self) __weak weakSelf = self; 488 | 489 | self.token = [self.realm 490 | addNotificationBlock:^(NSString *note, RLMRealm *realm) { 491 | 492 | if ([note isEqualToString:RLMRealmDidChangeNotification]) { 493 | 494 | // Pass the changes to the RealmNotificationManager 495 | [[RBQRealmNotificationManager defaultManager] sendNotificationsWithRealm:realm 496 | entityChanges:weakSelf.entityChanges]; 497 | 498 | // Nil the changes collection 499 | weakSelf.internalEntityChanges = nil; 500 | 501 | // Remove the token and nil it so we get dealloc 502 | [weakSelf.realm removeNotification:weakSelf.token]; 503 | weakSelf.token = nil; 504 | } 505 | }]; 506 | } 507 | 508 | - (void)tokenCheck 509 | { 510 | if (!self.token) { 511 | if ([NSThread isMainThread]) { 512 | [self registerChangeNotification]; 513 | } 514 | else { 515 | CFRunLoopPerformBlock(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, ^{ 516 | [self registerChangeNotification]; 517 | 518 | CFRunLoopStop(CFRunLoopGetCurrent()); 519 | }); 520 | 521 | CFRunLoopRun(); 522 | } 523 | } 524 | } 525 | 526 | #pragma mark - Helper 527 | 528 | - (RBQEntityChangesObject *)createOrRetrieveEntityChangesForClassName:(NSString *)className 529 | { 530 | if (!className) { 531 | return nil; 532 | } 533 | 534 | RBQEntityChangesObject *entityChangesObject; 535 | @synchronized(self.internalEntityChanges) { 536 | entityChangesObject = self.internalEntityChanges[className]; 537 | 538 | if (!entityChangesObject) { 539 | entityChangesObject = 540 | [RBQEntityChangesObject createEntityChangeObjectWithClassName:className]; 541 | 542 | self.internalEntityChanges[className] = entityChangesObject; 543 | } 544 | } 545 | 546 | return entityChangesObject; 547 | } 548 | 549 | @end -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RBQRealmNotificationManager 2 | Track RLMObject changes from Realm 3 | 4 | #### Note: 5 | If you plan to use this code seperate from https://github.com/Roobiq/RBQFetchedResultsController, then you need to also include https://github.com/Roobiq/RealmUtilities since RBQSafeRealmObject.h is a requirement (All changes from RBQRealmNotificationManager are reported via RBQSafeRealmObject's which are thread-safe representations of RLMObject). 6 | 7 | If I had more time, I would package this and the dependency into its own CocoaPod seperate from RBQFRC, but for now just use: 8 | ``` 9 | pod "RBQFetchedResultsController" 10 | ``` 11 | to get everything easily. 12 | 13 | For documentation on this class and more info see: https://github.com/Roobiq/RBQFetchedResultsController 14 | --------------------------------------------------------------------------------