Here is a sample code. I have a shared object and a dother object. Dother object must maintain its state when each property changes.
implementation
#import "GeneralObject.h" #import <objc/runtime.h> @implementation GeneralObject #pragma mark - Public + (instancetype)instanceWithDictionary:(NSDictionary *)aDictionary { return [[self alloc] initWithDictionary:aDictionary]; } - (instancetype)initWithDictionary:(NSDictionary *)aDictionary { aDictionary = [aDictionary clean]; for (NSString* propName in [self allPropertyNames]) { [self setValue:aDictionary[propName] forKey:propName]; } return self; } - (NSDictionary *)dictionaryValue { NSMutableDictionary *result = [NSMutableDictionary dictionary]; NSArray *propertyNames = [self allPropertyNames]; id object; for (NSString *key in propertyNames) { object = [self valueForKey:key]; if (object) { [result setObject:object forKey:key]; } } return result; } - (NSArray *)allPropertyNames { unsigned count; objc_property_t *properties = class_copyPropertyList([self class], &count); NSMutableArray *array = [NSMutableArray array]; unsigned i; for (i = 0; i < count; i++) { objc_property_t property = properties[i]; NSString *name = [NSString stringWithUTF8String:property_getName(property)]; [array addObject:name]; } free(properties); return array; } @end
and in the end we have a dother class, which should maintain its state on every change of any property
#import "GeneralObject.h" extern NSString *const kUserDefaultsUserKey; @interface DotherObject : GeneralObject @property (strong, nonatomic) NSString *firstName; @property (strong, nonatomic) NSString *lastName; @property (strong, nonatomic) NSString *email; @end
and implementation
#import "DotherObject.h" NSString *const kUserDefaultsUserKey = @"CurrentUserKey"; @implementation DotherObject - (instancetype)initWithDictionary:(NSDictionary *)dictionary { if (self = [super initWithDictionary:dictionary]) { for (NSString *key in [self allPropertyNames]) { [self addObserver:self forKeyPath:key options:NSKeyValueObservingOptionNew context:nil]; } } return self; } - (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSKeyValueChangeKey, id> *)change context:(nullable void *)context { NSDictionary *dict = [self dictionaryValue]; [[NSUserDefaults standardUserDefaults] setObject:dict forKey:kUserDefaultsUserKey]; [[NSUserDefaults standardUserDefaults] synchronize]; } - (NSString *)description { return [NSString stringWithFormat:@"%@; dict:\n%@", [super description], [self dictionaryValue]]; } @end
Happy coding!
WINSergey
source share