diff --git a/.travis.yml b/.travis.yml index 58ebf34..910ce19 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,5 @@ language: objective-c -osx_image: xcode63 +osx_image: xcode8 branches: only: - master @@ -9,4 +9,4 @@ before_install: - gem install xcpretty -N script: - xcodebuild -project Spread.xcodeproj -scheme "Spread" -sdk iphonesimulator - -destination "platform=iOS Simulator,name=iPhone 6" ONLY_ACTIVE_ARCH=NO test + -destination "platform=iOS Simulator,name=iPhone 7" ONLY_ACTIVE_ARCH=NO test diff --git a/Classes/Decoder.h b/Classes/Decoder.h new file mode 100644 index 0000000..ad37088 --- /dev/null +++ b/Classes/Decoder.h @@ -0,0 +1,46 @@ +// +// Mapper.h +// Mapper +// +// Created by Huy Pham on 3/26/15. +// Copyright (c) 2015 Katana. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface Decoder : NSObject +/** + * Auto Mapper properties object with dictionary/json. + * + * @param dictionary Data to Mapper. + * + * @return Object Mapper. + */ +- (instancetype)initWithDictionary:(nullable NSDictionary *)dictionary; + +/** + * Auto Mapper properties object with dictionary/json. + * + * @param dictionary Data to Mapper. + */ +- (void)initData:(nullable NSDictionary *)dictionary; + +/** + * Convert object to dictionary. + * + * @return Object dictionary. + */ +- (NSDictionary *)toDictionary; + +/** + * Object initial status. + * + * @return Initial state. + */ +- (BOOL)isInitiated; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Classes/Decoder.m b/Classes/Decoder.m new file mode 100644 index 0000000..32c56ae --- /dev/null +++ b/Classes/Decoder.m @@ -0,0 +1,342 @@ +// +// Mapper.m +// Mapper +// +// Created by Huy Pham on 3/26/15. +// Copyright (c) 2015 Katana. All rights reserved. +// + +#import +#import "Decoder.h" +#import + +static const char *getPropertyType(objc_property_t property) { + const char *attributes = property_getAttributes(property); + char buffer[1 + strlen(attributes)]; + strcpy(buffer, attributes); + char *state = buffer, *attribute; + while ((attribute = strsep(&state, ",")) != NULL) { + if (attribute[0] == 'T' && attribute[1] != '@') { + NSString *name = [[NSString alloc] initWithBytes:attribute + 1 + length:strlen(attribute) - 1 + encoding:NSASCIIStringEncoding]; + return (const char *)[name cStringUsingEncoding:NSASCIIStringEncoding]; + } + else if (attribute[0] == 'T' && attribute[1] == '@' && strlen(attribute) == 2) { + return "id"; + } + else if (attribute[0] == 'T' && attribute[1] == '@') { + NSString *name = [[NSString alloc] initWithBytes:attribute + 3 + length:strlen(attribute) - 4 + encoding:NSASCIIStringEncoding]; + return (const char *)[name cStringUsingEncoding:NSASCIIStringEncoding]; + } + } + return ""; +} + +@interface Attribute : NSObject + +@property (nonatomic, strong) NSString *name; +@property (nonatomic, strong) NSString *nameWithoutUnderscore; +@property (nonatomic, strong) NSString *type; + + +@end + +@implementation Attribute + +@end + +@interface Decoder() + +@property (nonatomic, getter=isInitiated) BOOL initiated; + +@end + +static NSDictionary *_attributes = nil; + +@implementation Decoder + ++ (NSArray *)attributesForClass:(Class)class { + NSString *classIdent = NSStringFromClass(class); + return [_attributes valueForKey:classIdent]; +} + ++ (void)setAttributes:(NSArray *)attributes forClass:(Class)class { + NSString *classIdent = NSStringFromClass(class); + if (_attributes) { + NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:attributes, classIdent, nil]; + [dic addEntriesFromDictionary:_attributes]; + _attributes = dic; + return; + } + _attributes = [NSDictionary dictionaryWithObjectsAndKeys:attributes, classIdent, nil]; +} + ++ (NSArray *)getAttributeForClass:(Class)class { + NSMutableArray *attributes = [NSMutableArray array]; + unsigned int outCount; + objc_property_t *properties = class_copyPropertyList(class, &outCount); + for(int i = 0; i < outCount; i++) { + objc_property_t property = properties[i]; + const char *propertyNameChar = property_getName(property); + if (propertyNameChar) { + @autoreleasepool { + const char *propertyTypeChar = getPropertyType(property); + NSString *propertyName = [NSString stringWithCString:propertyNameChar + encoding:NSUTF8StringEncoding]; + NSString *propertyType = [NSString stringWithCString:propertyTypeChar + encoding:NSUTF8StringEncoding]; + NSString *propertyNameStrippedUnderscore = [self getPropertyNameStrippedUnderscore:propertyName]; + + Attribute *attribute = [[Attribute alloc] init]; + attribute.name = propertyName; + attribute.nameWithoutUnderscore = propertyNameStrippedUnderscore; + attribute.type = propertyType; + + [attributes addObject:attribute]; + } + } + } + free(properties); + return attributes; +} + ++ (NSString *)getPropertyNameStrippedUnderscore:(NSString *)property { + if (!property) { + return nil; + } + if ([property length] == 0) { + return @""; + } + if ([property characterAtIndex:0] == '_') { + return [property substringFromIndex:1]; + } + return property; +} + +- (instancetype)init { + return [self initWithDictionary:nil]; +} + +- (instancetype)initWithDictionary:(NSDictionary *)dictionary { + _initiated = NO; + self = [super init]; + if (!self) { + return nil; + } + if (!dictionary || ![dictionary isKindOfClass:[NSDictionary class]]) { + SEL selector = NSSelectorFromString([NSString stringWithFormat:@"_%@:", + NSStringFromClass(self.class)]); + if ([self respondsToSelector:selector]) { + ((void (*)(id, SEL, id))[self methodForSelector:selector])(self, + selector, dictionary); + } else { + [self initData:nil]; + } + return self; + } + [self initData:dictionary]; + _initiated = YES; + return self; +} + +- (NSArray *)attributes { + Class class = [self class]; + NSArray *existedAttributes = [Decoder attributesForClass:class]; + if (existedAttributes) { + return existedAttributes; + } + NSMutableArray *attributes = [NSMutableArray array]; + + Class superClass = class; + while ([superClass superclass] != [Decoder class] && [superClass isSubclassOfClass:[Decoder class]]) { + NSArray *attrs = [Decoder getAttributeForClass:superClass]; + [attributes addObjectsFromArray:attrs]; + superClass = [superClass superclass]; + } + + [Decoder setAttributes:attributes + forClass:class]; + return attributes; +} + +- (void)initData:(NSDictionary *)dictionary { + // Automic + @synchronized (self) { + @autoreleasepool { + for(Attribute *attribute in [self attributes]) { + id value = [dictionary objectForKey:attribute.nameWithoutUnderscore]; + [self setProperty:attribute.name + propertyType:attribute.type + value:value]; + } + } + } +} + +- (void)setProperty:(NSString *)propertyName + propertyType:(NSString *)propertyType + value:(id)value { + id instanceType = [self valueForKey:propertyName]; + + // Init instance + if (!instanceType) { + if ([NSClassFromString(propertyType) isSubclassOfClass:[Decoder class]]) { + instanceType = [[NSClassFromString(propertyType) alloc] initWithDictionary:value]; + return [self setValue:instanceType + forKey:propertyName]; + } + instanceType = [NSClassFromString(propertyType) alloc]; + } + + // Alloc instance + if ([instanceType isKindOfClass:[NSArray class]]) { + instanceType = [NSArray alloc]; + } else if ([instanceType isKindOfClass:[NSMutableArray class]]){ + instanceType = [NSMutableArray alloc]; + } else if ([instanceType isKindOfClass:[NSDictionary class]]) { + instanceType = [NSDictionary alloc]; + } else if ([instanceType isKindOfClass:[NSMutableDictionary class]]) { + instanceType = [NSMutableDictionary alloc]; + } else if ([instanceType isKindOfClass:[NSString class]]) { + instanceType = [NSString alloc]; + } + + // Check value + if (value && value != [NSNull null]) { + if ([propertyType respondsToSelector:@selector(initData:)]) { + return [instanceType initData:value]; + } + + if ([instanceType respondsToSelector:@selector(initWithArray:)]) { + return [self setValue:[instanceType initWithArray:value] + forKey:propertyName]; + } + + if ([instanceType respondsToSelector:@selector(initWithDictionary:)]) { + return [self setValue:[instanceType initWithDictionary:value] + forKey:propertyName]; + } + return [self setValue:value + forKey:propertyName]; + } + + // Call default function + SEL selector = NSSelectorFromString([NSString stringWithFormat:@"_%@", propertyName]); + if ([self respondsToSelector:selector]) { + ((void (*)(id, SEL))[self methodForSelector:selector])(self, selector); + } else { + [self setValue:[instanceType init] + forKey:propertyName]; + } +} + +- (NSDictionary *)toDictionary { + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionary]; + for (Attribute *attribute in [self attributes]) { + id value = [self valueForKey:attribute.name]; + if ([[value class] isSubclassOfClass:[Decoder class]]) { + [mutableDictionary setObject:[value toDictionary] + forKey:attribute.name]; + continue; + } + if ([value isKindOfClass:[NSArray class]]){ + [mutableDictionary setObject:[self toArray:value] + forKey:attribute.name]; + continue; + } + [mutableDictionary setObject:[self toValue:value + key:attribute.name + type: attribute.type] + forKey:attribute.name]; + + } + return mutableDictionary; +} + +- (NSArray *)toArray:(NSArray *)array { + NSMutableArray *mutableArray = [NSMutableArray array]; + for (id value in array) { + if ([[value class] isSubclassOfClass:[Decoder class]]) { + [mutableArray addObject:[value toDictionary]]; + continue; + } + if ([value isKindOfClass:[NSArray class]]){ + [mutableArray addObject:[self toArray:value]]; + continue; + } + [mutableArray addObject:value]; + } + return mutableArray; +} + +- (id)toValue:(id)value key:(NSString *)key type:(NSString *)type { + if ([type isEqualToString:@"q"]) { + long long longValue = (long long)[value longLongValue]; + return @(longValue); + } + if ([type isEqualToString:@"Q"]) { + unsigned long long ulongValue = [value unsignedLongValue]; + return @(ulongValue); + } + + if ([type isEqualToString:@"B"]) { + BOOL boolValue = [value boolValue]; + return @(boolValue); + } + + if ([type isEqualToString:@"C"]) { + Boolean boolValue = [value boolValue]; + return @(boolValue); + } + + if ([type isEqualToString:@"d"]) { + double floatValue = [value floatValue]; + return @(floatValue); + } + + if ([type isEqualToString:@"{CGSize=dd}"]) { + CGSize size = [value CGSizeValue]; + NSMutableDictionary *sizeDictionary = [NSMutableDictionary dictionary]; + [sizeDictionary setValue:@(size.width) forKey:@"width"]; + [sizeDictionary setValue:@(size.height) forKey:@"height"]; + return sizeDictionary; + } + + if ([type isEqualToString:@"{CGRect={CGPoint=dd}{CGSize=dd}}"]) { + CGRect rect = [value CGRectValue]; + NSMutableDictionary *rectDictionary = [NSMutableDictionary dictionary]; + NSMutableDictionary *sizeDictionary = [NSMutableDictionary dictionary]; + [sizeDictionary setValue:@(rect.size.width) forKey:@"width"]; + [sizeDictionary setValue:@(rect.size.height) forKey:@"height"]; + NSMutableDictionary *originDictionary = [NSMutableDictionary dictionary]; + [originDictionary setValue:@(rect.origin.x) forKey:@"x"]; + [originDictionary setValue:@(rect.origin.y) forKey:@"y"]; + [rectDictionary setValue:sizeDictionary forKey:@"size"]; + [rectDictionary setValue:originDictionary forKey:@"origin"]; + return rectDictionary; + } + + if ([type isEqualToString:@"{CGPoint=dd}"]) { + CGPoint point = [value CGPointValue]; + NSMutableDictionary *pointDictionary = [NSMutableDictionary dictionary]; + [pointDictionary setValue:@(point.x) forKey:@"x"]; + [pointDictionary setValue:@(point.y) forKey:@"y"]; + return pointDictionary; + } + + if ([type isEqualToString:@"NSString"]) { + return value; + } + // Add more value serializer here. + + return value; +} + +- (BOOL)isInitiated { + return _initiated; +} + +@end diff --git a/Classes/SModel.h b/Classes/Mapper.h similarity index 72% rename from Classes/SModel.h rename to Classes/Mapper.h index 8524c51..7cb7ece 100644 --- a/Classes/SModel.h +++ b/Classes/Mapper.h @@ -1,56 +1,34 @@ // -// SModel.h -// Spread +// Mapper.h +// Mapper // // Created by Huy Pham on 3/26/15. // Copyright (c) 2015 Katana. All rights reserved. // -#import +#import "Decoder.h" + +NS_ASSUME_NONNULL_BEGIN /** - * SModel events description. + * Mapper events description. */ -typedef NS_ENUM(NSInteger, SModelEvent){ +typedef NS_ENUM(NSInteger, MapperEvent){ /** * Model will trigger event when value of data is increased. */ - SModelEventOnIncrease = 0x01, + MapperEventOnIncrease = 0x01, /** * Model will trigger event when value of data is decreased. */ - SModelEventOnDecrease = 0x02, + MapperEventOnDecrease = 0x02, /** * Model will trigger event when value of data is changed. */ - SModelEventOnChange = 0x03 + MapperEventOnChange = 0x03 }; -@interface SModel : NSObject - -/** - * Auto mapping properties object with dictionary/json. - * - * @param dictionary Data to mapping. - * - * @return Object mapping. - */ -- (instancetype)initWithDictionary:(NSDictionary *)dictionary; - -/** - * Auto mapping properties object with dictionary/json. - * - * @param dictionary Data to mapping. - */ -- (void)initData:(NSDictionary *)dictionary; - -/** - * Convert object to dictionary. - * - * @return Object dictionary. - */ -- (NSDictionary *)toDictionary; - +@interface Mapper : Decoder /** * Register reaction for property on an event. * @@ -59,7 +37,7 @@ typedef NS_ENUM(NSInteger, SModelEvent){ * @param reaction Reaction handler. */ - (void)property:(NSString *)property - onEvent:(SModelEvent)event + onEvent:(MapperEvent)event reaction:(void(^)(id oldValue, id newValue))reaction; /** @@ -70,7 +48,7 @@ typedef NS_ENUM(NSInteger, SModelEvent){ * @param reaction Reaction handler. */ - (void)properties:(NSArray *)properties - onEvent:(SModelEvent)event + onEvent:(MapperEvent)event reaction:(void(^)(id oldValue, id newValue))reaction; /** @@ -78,26 +56,26 @@ typedef NS_ENUM(NSInteger, SModelEvent){ * * @param property Property key path. * @param target Object trigger event. - * @param action A selector. + * @param selector A selector. * @param event Event description. */ - (void)property:(NSString *)property target:(id)target selector:(SEL)selector - onEvent:(SModelEvent)event; + onEvent:(MapperEvent)event; /** * Register action for multi properties on an event. * * @param properties List of properties key path. * @param target Object trigger event. - * @param action A selector. + * @param selector A selector. * @param event Event description. */ - (void)properties:(NSArray *)properties target:(id)target selector:(SEL)selector - onEvent:(SModelEvent)event; + onEvent:(MapperEvent)event; /** * Remove reactions handler for property on event. @@ -106,7 +84,7 @@ typedef NS_ENUM(NSInteger, SModelEvent){ * @param event Event description. */ - (void)removeReactionsForProperty:(NSString *)property - onEvent:(SModelEvent)event; + onEvent:(MapperEvent)event; /** * Remove all reactions handler for property. @@ -122,7 +100,7 @@ typedef NS_ENUM(NSInteger, SModelEvent){ * @param event Event description. */ - (void)removeReactionsForProperties:(NSArray *)properties - onEvent:(SModelEvent)event; + onEvent:(MapperEvent)event; /** * Remove all reactions for multi properties. @@ -147,7 +125,7 @@ typedef NS_ENUM(NSInteger, SModelEvent){ - (void)removeActionsForProperty:(NSString *)property target:(id)target selector:(SEL)selector - onEvent:(SModelEvent)event; + onEvent:(MapperEvent)event; /** * Remove actions of property with target for all event. @@ -169,7 +147,7 @@ typedef NS_ENUM(NSInteger, SModelEvent){ /** * Remove actions for multi properties with target on event. * - * @param property Property key path. + * @param properties Property key path. * @param target The target. * @param selector The selector to remove. * @param event Event description. @@ -177,7 +155,7 @@ typedef NS_ENUM(NSInteger, SModelEvent){ - (void)removeActionsForProperties:(NSArray *)properties target:(id)target selector:(SEL)selector - onEvent:(SModelEvent)event; + onEvent:(MapperEvent)event; /** * Remove actions for multi property with target. @@ -200,13 +178,6 @@ typedef NS_ENUM(NSInteger, SModelEvent){ */ - (void)removeAllActions; -/** - * Set source url for model. - * - * @param sourceUrl The source url. - */ -- (void)setSourceUrl:(NSString *)sourceUrl; - /** * Get source url. * @@ -214,12 +185,9 @@ typedef NS_ENUM(NSInteger, SModelEvent){ */ - (NSString *)getSourceUrl; -/** - * Set key path for data source fetch from source url. - * - * @param sourceKeyPath The source key path. - */ -- (void)setSourceKeyPath:(NSString *)sourceKeyPath; +- (NSString *)getSourceMethod; + +- (NSDictionary *)getSourceParameters; /** * Get data key path. @@ -236,13 +204,9 @@ typedef NS_ENUM(NSInteger, SModelEvent){ /** * Fetch data in background and handle data when fetch data completed. */ -- (void)fetchInBackground:(void(^)(id response, NSError *error))completion; - -/** - * Object initial status. - * - * @return Initial state. - */ -- (BOOL)isInitiated; +- (void)fetchInBackground:(nullable void(^)(id response, NSError * _Nullable error))completion; +- (BOOL)isFetching; @end + +NS_ASSUME_NONNULL_END diff --git a/Classes/Mapper.m b/Classes/Mapper.m new file mode 100644 index 0000000..69fbf7f --- /dev/null +++ b/Classes/Mapper.m @@ -0,0 +1,545 @@ +// +// Mapper.m +// Mapper +// +// Created by Huy Pham on 3/26/15. +// Copyright (c) 2015 Katana. All rights reserved. +// + +static void * const MapperContext = (void*)&MapperContext; + +#import "Mapper.h" +#import "MapperUtils.h" +#import "Spread.h" + +@interface MapperReaction : NSObject + +@property (nonatomic, copy) NSString *keyPath; +@property (nonatomic) MapperEvent event; +@property (nonatomic, copy) void (^react)(id, id); + +@end + +@implementation MapperReaction + +@end + +@interface MapperAction : NSObject + +@property (nonatomic, copy) NSString *keyPath; +@property (nonatomic) MapperEvent event; +@property (nonatomic, weak) id target; +@property (nonatomic) SEL selector; + +@end + +@implementation MapperAction + +@end + +@interface Mapper() + +@property (nonatomic, getter=isFetching) BOOL fetching; + +@end + +@implementation Mapper { + + // Store callback reaction. + NSMutableArray *_reactions; + + // Store action with target. + NSMutableArray *_actions; + + // Store keyobserver. + NSMutableArray *_keyPaths; +} + +// Lazy initial array to store reaction. +- (NSMutableArray *)reactions { + @synchronized(_reactions) { + if (!_reactions) { + _reactions = [NSMutableArray array]; + } + } + return _reactions; +} + +// Lazy initial array to store action. +- (NSMutableArray *)actions { + @synchronized(_actions) { + if (!_actions) { + _actions = [NSMutableArray array]; + } + } + return _actions; +} + +- (NSMutableArray *)keyPaths { + @synchronized(_keyPaths) { + if (!_keyPaths) { + _keyPaths = [NSMutableArray array]; + } + } + return _keyPaths; +} + +- (instancetype)init { + self = [super init]; + if (self) { + [self commonInit]; + } + return self; +} + +- (void)commonInit { + _actions = nil; + _reactions = nil; + _fetching = NO; +} + +// Check keys path existed +- (BOOL)keyPathExisted:(NSString *)keyPath { + @synchronized (_keyPaths) { + for (NSString *key in _keyPaths) { + if ([key isEqualToString:keyPath]) { + return YES; + } + } + return NO; + } +} + +- (void)addKeyPath:(NSString *)keyPath { + [[self keyPaths] addObject:[keyPath copy]]; +} + +- (void)removeKeyPath:(NSString *)keyPath { + @synchronized (_keyPaths) { + NSMutableArray *keysToDelete = [NSMutableArray array]; + for (NSString *key in _keyPaths) { + if ([key isEqualToString:keyPath]) { + [keysToDelete addObject:key]; + } + } + [_keyPaths removeObjectsInArray:keysToDelete]; + } +} + +// Get reaction of property on event. +- (NSArray *)getReactionsOfProperty:(NSString *)property + onEvent:(MapperEvent)event { + NSMutableArray *reactions = [NSMutableArray array]; + @synchronized (_reactions) { + for (MapperReaction *reaction in _reactions) { + if ([reaction.keyPath isEqualToString:property] + && reaction.event == event) { + [reactions addObject:reaction]; + } + } + return reactions; + } +} + +// Get reactions of property. +- (NSArray *)getReactionsOfProperty:(NSString *)property { + NSMutableArray *reactions = [NSMutableArray array]; + @synchronized (_reactions) { + for (MapperReaction *reaction in _reactions) { + if ([reaction.keyPath isEqualToString:property]) { + [reactions addObject:reaction]; + } + } + return reactions; + } +} + +- (NSArray *)getActionsOfProperty:(NSString *)property + target:(id)target + selector:(SEL)selector + onEvent:(MapperEvent)event { + NSMutableArray *actions = [NSMutableArray array]; + @synchronized (_actions) { + for (MapperAction *action in _actions) { + if ([action.keyPath isEqualToString:property] + && [action.target isEqual:target] + && action.selector == selector + && action.event == event) { + [actions addObject:action]; + } + } + return actions; + } +} + +- (NSArray *)getActionsOfProperty:(NSString *)property + target:(id)target + selector:(SEL)selector { + NSMutableArray *actions = [NSMutableArray array]; + @synchronized (_actions) { + for (MapperAction *action in _actions) { + if ([action.keyPath isEqualToString:property] + && [action.target isEqual:target] + && action.selector == selector) { + [actions addObject:action]; + } + } + return actions; + } +} + +- (NSArray *)getActionsOfProperty:(NSString *)property + target:(id)target { + NSMutableArray *actions = [NSMutableArray array]; + @synchronized (_actions) { + for (MapperAction *action in _actions) { + if ([action.keyPath isEqualToString:property] + && [action.target isEqual:target]) { + [actions addObject:action]; + } + } + return actions; + } +} + +- (NSArray *)getActionsOfProperty:(NSString *)property + onEvent:(MapperEvent)event { + NSMutableArray *actions = [NSMutableArray array]; + @synchronized (_actions) { + for (MapperAction *action in _actions) { + if ([action.keyPath isEqualToString:property] + && action.event == event) { + [actions addObject:action]; + } + } + return actions; + } +} + +// Get action of property. +- (NSArray *)getActionsOfProperty:(NSString *)property { + NSMutableArray *actions = [NSMutableArray array]; + @synchronized (_actions) { + for (MapperAction *action in _actions) { + if ([action.keyPath isEqualToString:property]) { + [actions addObject:action]; + } + } + return actions; + } +} + +- (void)registerObserverForKeyPath:(NSString *)keyPath { + if (![self keyPathExisted:keyPath]) { + @try { + @synchronized(_keyPaths) { + [self addKeyPath:keyPath]; + [self addObserver:self + forKeyPath:keyPath + options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) + context:MapperContext]; + } + } + @catch (NSException *exception) { + NSLog(@"[Register] Exception: %@", exception); + } + } +} + +- (void)removeObserverForKeyPath:(NSString *)keyPath { + if ([self keyPathExisted:keyPath]) { + @try { + @synchronized(_keyPaths) { + [self removeKeyPath:keyPath]; + [self removeObserver:self + forKeyPath:keyPath + context:MapperContext]; + } + } + @catch (NSException *exception) { + NSLog(@"[Remove action] Exception: %@", exception); + } + } +} + +- (void)removeAllObservers { + @synchronized(_keyPaths) { + for (NSString *keyPath in _keyPaths) { + @try { + [self removeObserver:self + forKeyPath:keyPath + context:MapperContext]; + } + @catch (NSException *exception) { + NSLog(@"[Remove action] Exception: %@", exception); + } + } + } +} + +- (void)removeActions:(NSArray *)actions + observerForKeyPath:(NSString *)keyPath { + NSInteger observerCount = [[self getActionsOfProperty:keyPath] count] + + [[self getReactionsOfProperty:keyPath] count]; + if (observerCount == 0) return; + [_actions removeObjectsInArray:actions]; + [self removeObserverForKeyPath:keyPath]; +} + +- (void)removeReactions:(NSArray *)reactions + observerForKeyPath:(NSString *)keyPath { + NSInteger observerCount = [[self getActionsOfProperty:keyPath] count] + + [[self getReactionsOfProperty:keyPath] count]; + if (observerCount == 0) return; + [_reactions removeObjectsInArray:reactions]; + [self removeObserverForKeyPath:keyPath]; +} + +// IMPLEMENT +- (void)property:(NSString *)property + onEvent:(MapperEvent)event + reaction:(void (^)(id, id))reaction { + [self registerObserverForKeyPath:property]; + MapperReaction *modelReaction = [[MapperReaction alloc] init]; + modelReaction.keyPath = property; + modelReaction.react = reaction; + modelReaction.event = event; + [[self reactions] addObject:modelReaction]; +} + +- (void)property:(NSString *)property + target:(id)target + selector:(SEL)selector + onEvent:(MapperEvent)event { + if ([[self getActionsOfProperty:property + target:target + selector:selector + onEvent:event] count] > 0) { +#ifdef DEBUG + NSLog(@"Duplicated register keyPath: %@", property); +#endif + return; + } + [self registerObserverForKeyPath:property]; + MapperAction *modelAction = [[MapperAction alloc] init]; + modelAction.keyPath = property; + modelAction.target = target; + modelAction.selector = selector; + modelAction.event = event; + [[self actions] addObject:modelAction]; +} + +- (void)properties:(NSArray *)properties + onEvent:(MapperEvent)event + reaction:(void (^)(id, id))reaction { + for (NSString *property in properties) { + [self property:property + onEvent:event + reaction:reaction]; + } +} + +- (void)properties:(NSArray *)properties + target:(id)target + selector:(SEL)selector + onEvent:(MapperEvent)event { + for (NSString *property in properties) { + [self property:property + target:target + selector:selector + onEvent:event]; + } +} + +- (void)removeReactionsForProperty:(NSString *)property + onEvent:(MapperEvent)event { + NSArray *reactions = [self getReactionsOfProperty:property + onEvent:event]; + if ([reactions count] == 0) return; + [self removeReactions:reactions + observerForKeyPath:property]; +} + +- (void)removeReactionsForProperty:(NSString *)property { + NSArray *reactions = [self getReactionsOfProperty:property]; + if ([reactions count] == 0) return; + [self removeReactions:reactions + observerForKeyPath:property]; +} + +- (void)removeReactionsForProperties:(NSArray *)properties + onEvent:(MapperEvent)event { + for (NSString *property in properties) { + [self removeReactionsForProperty:property + onEvent:event]; + } +} + +- (void)removeReactionsForProperties:(NSArray *)properties { + for (NSString *property in properties) { + [self removeReactionsForProperty:property]; + } +} + +- (void)removeAllReactions { + while ([_reactions count] > 0) { + MapperReaction *reaction = [_reactions firstObject]; + if (reaction) { + [self removeReactionsForProperty:reaction.keyPath]; + } + } +} + +- (void)removeActionsForProperty:(NSString *)property + target:(id)target + selector:(SEL)selector + onEvent:(MapperEvent)event { + NSArray *actions = [self getActionsOfProperty:property + target:target + selector:selector + onEvent:event]; + if ([actions count] == 0) return; + [self removeActions:actions + observerForKeyPath:property]; +} + +- (void)removeActionsForProperty:(NSString *)property + target:(id)target { + NSArray *actions = [self getActionsOfProperty:property + target:target]; + if ([actions count] == 0) return; + [self removeActions:actions + observerForKeyPath:property]; +} + +- (void)removeActionsForProperty:(NSString *)property { + NSArray *actions = [self getActionsOfProperty:property]; + if ([actions count] == 0) return; + [self removeActions:actions + observerForKeyPath:property]; +} + +- (void)removeActionsForProperties:(NSArray *)properties + target:(id)target + selector:(SEL)selector + onEvent:(MapperEvent)event { + for (NSString *property in properties) { + [self removeActionsForProperty:property + target:target + selector:selector + onEvent:event]; + } +} + +- (void)removeActionsForProperties:(NSArray *)properties + target:(id)target { + for (NSString *property in properties) { + [self removeActionsForProperty:property + target:target]; + } +} + +- (void)removeActionsForProperties:(NSArray *)properties { + for (NSString *property in properties) { + [self removeActionsForProperty:property]; + } +} + +- (void)removeAllActions { + while ([_actions count] > 0) { + MapperAction *action = [_actions firstObject]; + if (action) { + [self removeActionsForProperty:action.keyPath]; + } + } +} + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(id)object + change:(NSDictionary *)change + context:(void *)context { + id oldValue = change[@"old"]; + id newValue = change[@"new"]; + MapperEvent event = MapperEventOnChange; + NSArray *reactions = [self getReactionsOfProperty:keyPath + onEvent:event]; + for (MapperReaction *reaction in reactions) { + reaction.react(oldValue, newValue); + } + + // Automatic delete action when target become nil. + NSMutableArray *actionsToDelete = [NSMutableArray array]; + NSArray *actions = [self getActionsOfProperty:keyPath + onEvent:event]; + NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init]; + [backgroundQueue addOperationWithBlock:^{ + for (MapperAction *action in actions) { + id target = action.target; + if (target) { + ((void (*)(id, SEL))[target methodForSelector:action.selector])(target, + action.selector); + continue; + } + [actionsToDelete addObject:action]; + } + for (MapperAction *action in actionsToDelete) { + [self removeActionsForProperty:action.keyPath + target:action.target]; + } + }]; +} + +- (void)fetchInBackground { + [self fetchInBackground: nil]; +} + +- (void)fetchInBackground:(void (^)(id, NSError *))completion { + if (self.isFetching) { + return; + } + _fetching = YES; + __weak Mapper *weakSelf = self; + [MapperUtils request:[self getSourceUrl] + method:[self getSourceMethod] + parameters:[self getSourceParameters] + headers:[Spread getNetworkHeaders] + completionHandler:^(id response, NSError *error) { + _fetching = NO; + NSDictionary *data = [MapperUtils getDataFrom:response + WithKeyPath:[weakSelf getSourceKeyPath]]; + + + if (data) { + [weakSelf initData:data]; + } + if (completion) { + completion(data, error); + } + }]; +} + +- (NSString *)getSourceKeyPath { + return @""; +} + +- (NSString *)getSourceUrl { + return @""; +} + +- (NSString *)getSourceMethod { + return @"GET"; +} + +- (NSDictionary *)getSourceParameters { + return nil; +} + +- (BOOL)isFetching { + return _fetching; +} + +- (void)dealloc { + [self removeAllObservers]; +} + +@end diff --git a/Classes/SUtils.h b/Classes/MapperUtils.h similarity index 83% rename from Classes/SUtils.h rename to Classes/MapperUtils.h index 32fcff0..220142f 100644 --- a/Classes/SUtils.h +++ b/Classes/MapperUtils.h @@ -1,6 +1,6 @@ // -// SUtils.h -// Spread +// MapperUtils.h +// Mapper // // Created by Huy Pham on 4/9/15. // Copyright (c) 2015 Katana. All rights reserved. @@ -8,7 +8,7 @@ #import -@interface SUtils : NSObject +@interface MapperUtils : NSObject @property (nonatomic, strong) NSOperationQueue *operationQueue; @@ -17,6 +17,7 @@ + (void)request:(NSString *)url method:(NSString *)method parameters:(NSDictionary *)parameters + headers:(NSDictionary *)headers completionHandler:(void(^)(id, NSError *))completion; + (NSDictionary *)getDataFrom:(NSDictionary *)data diff --git a/Classes/SUtils.m b/Classes/MapperUtils.m similarity index 66% rename from Classes/SUtils.m rename to Classes/MapperUtils.m index a855103..5a3b9eb 100644 --- a/Classes/SUtils.m +++ b/Classes/MapperUtils.m @@ -1,6 +1,6 @@ // -// SUtils.m -// Spread +// MapperUtils.m +// Mapper // // Created by Huy Pham on 4/9/15. // Copyright (c) 2015 Katana. All rights reserved. @@ -8,12 +8,11 @@ #define API_TIMEOUT_INTERVAL 20.0 -#import "SUtils.h" +#import "MapperUtils.h" -@implementation SUtils +@implementation MapperUtils - (instancetype)init { - self = [super init]; if (!self) { return nil; @@ -23,13 +22,11 @@ - (instancetype)init { } - (void)commonInit { - _operationQueue = [[NSOperationQueue alloc] init]; [_operationQueue setMaxConcurrentOperationCount:10]; } + (instancetype)sharedInstance { - static dispatch_once_t once; static id sharedInstance; dispatch_once(&once, ^{ @@ -39,7 +36,6 @@ + (instancetype)sharedInstance { } + (NSString *)getGETParametersString:(NSDictionary *)dictionary { - NSString *stringParameters = @""; if (dictionary) { NSArray *allKey = [dictionary allKeys]; @@ -57,7 +53,6 @@ + (NSString *)getGETParametersString:(NSDictionary *)dictionary { } + (NSData *)getPOSTParameters:(NSDictionary *)dictionary { - NSData *postdata = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:NULL]; @@ -67,50 +62,70 @@ + (NSData *)getPOSTParameters:(NSDictionary *)dictionary { + (void)request:(NSString *)url method:(NSString *)method parameters:(NSDictionary *)parameters + headers:(NSDictionary *)headers completionHandler:(void(^)(id, NSError *))completion { - - // Make request. NSURL *requestUrl = nil; + NSString *requestMethod = [method uppercaseString]; + if (![requestMethod isEqualToString:@"GET"] && + ![requestMethod isEqualToString:@"POST"] && + ![requestMethod isEqualToString:@"PUT"] && + ![requestMethod isEqualToString:@"DELETE"]) { + NSLog(@"Unsupport method %@", method); + return; + } if ([method isEqualToString:@"GET"] && parameters) { requestUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", url, [self getGETParametersString:parameters]]]; } else { requestUrl = [NSURL URLWithString:url]; } NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:requestUrl]; + for (NSString *key in [headers allKeys]) { + NSString *value = [headers valueForKey:key]; + if (!value) { + continue; + } + if (![value isEqualToString:@""]) { + [request setValue:value + forHTTPHeaderField:key]; + } + } NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); [request setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; - [request setHTTPMethod:method]; - if (parameters && ([method isEqualToString:@"POST"] - || [method isEqualToString:@"PUT"] - || [method isEqualToString:@"DELETE"])) { + [request setHTTPMethod:requestMethod]; + if (parameters) { [request setHTTPBody:[self getPOSTParameters:parameters]]; } [request setTimeoutInterval:API_TIMEOUT_INTERVAL]; - [NSURLConnection sendAsynchronousRequest:request queue:[[self sharedInstance] operationQueue] - completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { - if (connectionError) { - completion(nil, connectionError); - } else { - NSError *error; - NSDictionary *jsonObj = [NSJSONSerialization JSONObjectWithData:data - options:NSJSONReadingAllowFragments - error:&error]; - completion(jsonObj, nil); - } - }]; + NSURLSession *session = [NSURLSession sharedSession]; + [[session dataTaskWithRequest:request + completionHandler:^(NSData *data, + NSURLResponse *response, + NSError *error) { + if (error) { + completion(nil, error); + } else { + NSError *error; + NSDictionary *jsonObj = [NSJSONSerialization JSONObjectWithData:data + options:NSJSONReadingAllowFragments + error:&error]; + completion(jsonObj, error); + } + }] resume]; } + (NSDictionary *)getDataFrom:(NSDictionary *)data WithKeyPath:(NSString *)keyPath { - - if (!keyPath || [keyPath isEqualToString:@""]) { + if ([keyPath isEqualToString:@""]) { return data; } NSArray *arrayOfKeyPath = [keyPath componentsSeparatedByString:@"/"]; NSDictionary *value = data; for (NSString *path in arrayOfKeyPath) { value = [value valueForKey:path]; + if ([value isKindOfClass:[NSArray class]]) { + return nil; + } } return value; } diff --git a/Classes/NSArray+Spread.h b/Classes/NSArray+Spread.h index 38ce857..205fe1e 100644 --- a/Classes/NSArray+Spread.h +++ b/Classes/NSArray+Spread.h @@ -8,8 +8,12 @@ #import +NS_ASSUME_NONNULL_BEGIN + @interface NSArray (Spread) - (NSArray *)filter:(BOOL (^)(id))filter; @end + +NS_ASSUME_NONNULL_END diff --git a/Classes/NSArray+Spread.m b/Classes/NSArray+Spread.m index 71c919b..ac9420e 100644 --- a/Classes/NSArray+Spread.m +++ b/Classes/NSArray+Spread.m @@ -11,7 +11,6 @@ @implementation NSArray (Spread) - (NSArray *)filter:(BOOL (^)(id))filter { - NSMutableArray *array = [NSMutableArray array]; for (id model in self) { if (filter(model)) { diff --git a/Classes/SModel.m b/Classes/SModel.m deleted file mode 100644 index 9cb681e..0000000 --- a/Classes/SModel.m +++ /dev/null @@ -1,652 +0,0 @@ -// -// SModel.m -// Spread -// -// Created by Huy Pham on 3/26/15. -// Copyright (c) 2015 Katana. All rights reserved. -// - -static void * SPreadContext = &SPreadContext; - -#import "SModel.h" - -#import "SUtils.h" -#import - -// Magic, do not touch. -static const char *getPropertyType(objc_property_t property) { - - const char *attributes = property_getAttributes(property); - char buffer[1 + strlen(attributes)]; - strcpy(buffer, attributes); - char *state = buffer, *attribute; - while ((attribute = strsep(&state, ",")) != NULL) { - if (attribute[0] == 'T' && attribute[1] != '@') { - NSString *name = [[NSString alloc] initWithBytes:attribute + 1 - length:strlen(attribute) - 1 - encoding:NSASCIIStringEncoding]; - - return (const char *)[name cStringUsingEncoding:NSASCIIStringEncoding]; - } - else if (attribute[0] == 'T' && attribute[1] == '@' && strlen(attribute) == 2) { - return "id"; - } - else if (attribute[0] == 'T' && attribute[1] == '@') { - NSString *name = [[NSString alloc] initWithBytes:attribute + 3 - length:strlen(attribute) - 4 - encoding:NSASCIIStringEncoding]; - - return (const char *)[name cStringUsingEncoding:NSASCIIStringEncoding]; - } - } - return ""; -} - -@interface SModelReaction : NSObject - -@property (nonatomic, copy) NSString *keyPath; -@property (nonatomic) SModelEvent event; -@property (nonatomic, copy) void (^react)(id, id); - -@end - -@implementation SModelReaction - -@end - -@interface SModelAction : NSObject - -@property (nonatomic, copy) NSString *keyPath; -@property (nonatomic) SModelEvent event; -@property (nonatomic, weak) id target; -@property (nonatomic) SEL selector; - -@end - -@implementation SModelAction - -@end - -@interface SModel() - -@property (nonatomic, copy) NSString *sourceUrl; -@property (nonatomic, copy) NSString *sourceKeyPath; -@property (nonatomic, getter=isInitiated) BOOL initiated; - -@end - -@implementation SModel { - - // Store callback reaction. - NSMutableArray *_reactions; - - // Store action with target. - NSMutableArray *_actions; -} - -// Lazy initial array to store reaction. -- (NSMutableArray *)reactions { - - @synchronized(self) { - if (!_reactions) { - _reactions = [NSMutableArray array]; - } - } - return _reactions; -} - -// Lazy initial array to store action. -- (NSMutableArray *)actions { - - @synchronized(self) { - if (!_actions) { - _actions = [NSMutableArray array]; - } - } - return _actions; -} - - -- (instancetype)initWithDictionary:(NSDictionary *)dictionary { - - self = [super init]; - if (!self) { - return nil; - } - if (!dictionary || ![dictionary isKindOfClass:[NSDictionary class]]) { - return self; - } - [self commonInit]; - [self initData:dictionary]; - return self; -} - -- (void)commonInit { - - _sourceKeyPath = @""; - _sourceUrl = nil; - _initiated = NO; -} - -// Return name tripped underscore -- (NSString *)getPropertyNameStrippedUnderscore:(NSString *)property { - - if (!property) { - return nil; - } - if ([property length] == 0) { - return @""; - } - if ([property characterAtIndex:0] == '_') { - return [property substringFromIndex:1]; - } - return property; -} - -- (void)initData:(NSDictionary *)dictionary { - - unsigned int outCount; - objc_property_t *properties = class_copyPropertyList([self class], &outCount); - for(int i = 0; i < outCount; i++) { - objc_property_t property = properties[i]; - const char *propName = property_getName(property); - if (propName) { - const char *propType = getPropertyType(property); - NSString *propertyName = [NSString stringWithCString:propName - encoding:NSUTF8StringEncoding]; - NSString *propertyType = [NSString stringWithCString:propType - encoding:NSUTF8StringEncoding]; - id instanceType = [NSClassFromString(propertyType) alloc]; - id value = [dictionary valueForKey:[self getPropertyNameStrippedUnderscore:propertyName]]; - if (value && value != [NSNull null]) { - if ([instanceType respondsToSelector:@selector(initWithDictionary:)]) { - [self setValue:[instanceType initWithDictionary:value] forKey:propertyName]; - } else if ([instanceType respondsToSelector:@selector(initWithArray:)]) { - [self setValue:[instanceType initWithArray:value] forKey:propertyName]; - } else { - [self setValue:value forKey:propertyName]; - } - } else { - SEL selector = NSSelectorFromString([NSString stringWithFormat:@"_%@", propertyName]); - if ([self respondsToSelector:selector]) { - ((void (*)(id, SEL))[self methodForSelector:selector])(self, selector); - } else { - if ([instanceType respondsToSelector:@selector(init)]) { - [self setValue:[instanceType init] forKey:propertyName]; - } - } - } - } - } - free(properties); - _initiated = YES; -} - -- (NSDictionary *)toDictionary { - - NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionary]; - unsigned int outCount; - objc_property_t *properties = class_copyPropertyList([self class], &outCount); - for(int i = 0; i < outCount; i++) { - objc_property_t property = properties[i]; - const char *propName = property_getName(property); - NSString *propertyName = [NSString stringWithCString:propName encoding:NSUTF8StringEncoding]; - id value = [self valueForKey:propertyName]; - if (value) { - NSString *propertyNameStrippedUnderscore = [self getPropertyNameStrippedUnderscore:propertyName]; - if ([[value class] isSubclassOfClass:[SModel class]]) { - [mutableDictionary setObject:[value toDictionary] - forKey:propertyNameStrippedUnderscore]; - } else if ([value isKindOfClass:[NSArray class]]) { - [mutableDictionary setObject:[self arraySerialization:value] - forKey:propertyNameStrippedUnderscore]; - } else if ([value isKindOfClass:[NSDictionary class]]) { - [mutableDictionary setObject:[self dictionarySerialization:value] - forKey:propertyNameStrippedUnderscore]; - } else { - [mutableDictionary setValue:value - forKey:propertyNameStrippedUnderscore]; - } - } - } - free(properties); - return [mutableDictionary copy]; -} - -- (NSDictionary *)dictionarySerialization:(NSDictionary *)dictionary { - - NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionary]; - for (NSString *key in [dictionary allKeys]) { - id value = [dictionary valueForKey:key]; - if ([[value class] isSubclassOfClass:[SModel class]]) { - [mutableDictionary setObject:[value toDictionary] - forKey:key]; - } else if ([value isKindOfClass:[NSArray class]]){ - [mutableDictionary setObject:[self arraySerialization:value] - forKey:key]; - } else if ([value isKindOfClass:[NSDictionary class]]) { - [mutableDictionary setObject:[self dictionarySerialization:value] - forKey:key]; - } else { - [mutableDictionary setObject:value - forKey:key]; - } - } - return [mutableDictionary copy]; -} - -- (NSArray *)arraySerialization:(NSArray *)array { - - NSMutableArray *mutableArray = [NSMutableArray array]; - for (id value in array) { - if ([[value class] isSubclassOfClass:[SModel class]]) { - [mutableArray addObject:[value toDictionary]]; - } else if ([value isKindOfClass:[NSArray class]]){ - [mutableArray addObject:[self arraySerialization:value]]; - } else if ([value isKindOfClass:[NSDictionary class]]) { - [mutableArray addObject:[self dictionarySerialization:value]]; - } else { - [mutableArray addObject:value]; - } - } - return [mutableArray copy]; -} - -// HELPER FUNCTION. - -// Get reaction of property on event. -- (NSArray *)getReactionsOfProperty:(NSString *)property - onEvent:(SModelEvent)event { - - NSMutableArray *reactions = [NSMutableArray array]; - for (SModelReaction *reaction in [self reactions]) { - if ([reaction.keyPath isEqualToString:property] - && reaction.event == event) { - [reactions addObject:reaction]; - } - } - return reactions; -} - -// Get reactions of property. -- (NSArray *)getReactionsOfProperty:(NSString *)property { - - NSMutableArray *reactions = [NSMutableArray array]; - for (SModelReaction *reaction in [self reactions]) { - if ([reaction.keyPath isEqualToString:property]) { - [reactions addObject:reaction]; - } - } - return reactions; -} - -- (NSArray *)getActionsOfProperty:(NSString *)property - target:(id)target - selector:(SEL)selector - onEvent:(SModelEvent)event { - - NSMutableArray *actions = [NSMutableArray array]; - for (SModelAction *action in _actions) { - if ([action.keyPath isEqualToString:property] - && [action.target isEqual:target] - && action.selector == selector - && action.event == event) { - [actions addObject:action]; - } - } - return actions; -} - -- (NSArray *)getActionsOfProperty:(NSString *)property - target:(id)target - selector:(SEL)selector { - - NSMutableArray *actions = [NSMutableArray array]; - for (SModelAction *action in _actions) { - if ([action.keyPath isEqualToString:property] - && [action.target isEqual:target] - && action.selector == selector) { - [actions addObject:action]; - } - } - return actions; -} - -- (NSArray *)getActionsOfProperty:(NSString *)property - target:(id)target { - - NSMutableArray *actions = [NSMutableArray array]; - for (SModelAction *action in _actions) { - if ([action.keyPath isEqualToString:property] - && [action.target isEqual:target]) { - [actions addObject:action]; - } - } - return actions; -} - -- (NSArray *)getActionsOfProperty:(NSString *)property - onEvent:(SModelEvent)event { - - NSMutableArray *actions = [NSMutableArray array]; - for (SModelAction *action in _actions) { - if ([action.keyPath isEqualToString:property] - && action.event == event) { - [actions addObject:action]; - } - } - return actions; -} - -// Get action of property. -- (NSArray *)getActionsOfProperty:(NSString *)property { - - NSMutableArray *actions = [NSMutableArray array]; - for (SModelAction *action in _actions) { - if ([action.keyPath isEqualToString:property]) { - [actions addObject:action]; - } - } - return actions; -} - -- (void)registerObserverForKeyPath:(NSString *)keyPath { - - if ([[self getActionsOfProperty:keyPath] count] == 0 - && [[self getReactionsOfProperty:keyPath] count] == 0) { - [self addObserver:self - forKeyPath:keyPath - options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) - context:SPreadContext]; - } -} - -- (void)removeObserverForKeyPath:(NSString *)keyPath { - - if ([[self getActionsOfProperty:keyPath] count] == 0 - && [[self getReactionsOfProperty:keyPath] count] == 0) { - - [self removeObserver:self - forKeyPath:keyPath - context:SPreadContext]; - } -} - -// IMPLEMENT -- (void)property:(NSString *)property - onEvent:(SModelEvent)event - reaction:(void (^)(id, id))reaction { - - // Register observer. - [self registerObserverForKeyPath:property]; - SModelReaction *modelReaction = [[SModelReaction alloc] init]; - modelReaction.keyPath = property; - modelReaction.react = reaction; - modelReaction.event = event; - [[self reactions] addObject:modelReaction]; -} - -- (void)property:(NSString *)property - target:(id)target - selector:(SEL)selector - onEvent:(SModelEvent)event { - - if ([[self getActionsOfProperty:property - target:target - selector:selector - onEvent:event] count] > 0) { - NSLog(@"Duplicated register."); - return; - } - - // Register observer. - [self registerObserverForKeyPath:property]; - - SModelAction *modelAction = [[SModelAction alloc] init]; - modelAction.keyPath = property; - modelAction.target = target; - modelAction.selector = selector; - modelAction.event = event; - [[self actions] addObject:modelAction]; -} - -- (void)properties:(NSArray *)properties - onEvent:(SModelEvent)event - reaction:(void (^)(id, id))reaction { - - for (NSString *property in properties) { - [self property:property - onEvent:event - reaction:reaction]; - } -} - -- (void)properties:(NSArray *)properties - target:(id)target - selector:(SEL)selector - onEvent:(SModelEvent)event { - - for (NSString *property in properties) { - [self property:property - target:target - selector:selector - onEvent:event]; - } -} - -- (void)removeReactionsForProperty:(NSString *)property - onEvent:(SModelEvent)event { - - NSArray *reactions = [self getReactionsOfProperty:property - onEvent:event]; - if ([reactions count] == 0) return; - [_reactions removeObjectsInArray:reactions]; - [self removeObserverForKeyPath:property]; -} - -- (void)removeReactionsForProperty:(NSString *)property { - - NSArray *reactions = [self getReactionsOfProperty:property]; - if ([reactions count] == 0) return; - [_reactions removeObjectsInArray:reactions]; - [self removeObserverForKeyPath:property]; -} - -- (void)removeReactionsForProperties:(NSArray *)properties - onEvent:(SModelEvent)event { - - for (NSString *property in properties) { - [self removeReactionsForProperty:property - onEvent:event]; - } -} - -- (void)removeReactionsForProperties:(NSArray *)properties { - - for (NSString *property in properties) { - [self removeReactionsForProperty:property]; - } -} - -- (void)removeAllReactions { - - NSArray *reactions = [_reactions copy]; - for (SModelReaction *reaction in reactions) { - [self removeReactionsForProperty:reaction.keyPath]; - } -} - -- (void)removeActionsForProperty:(NSString *)property - target:(id)target - selector:(SEL)selector - onEvent:(SModelEvent)event { - - NSArray *actions = [self getActionsOfProperty:property - target:target - selector:selector - onEvent:event]; - if ([actions count] == 0) return; - [_actions removeObjectsInArray:actions]; - [self removeObserverForKeyPath:property]; -} - -- (void)removeActionsForProperty:(NSString *)property - target:(id)target { - - NSArray *actions = [self getActionsOfProperty:property - target:target]; - if ([actions count] == 0) return; - [_actions removeObjectsInArray:actions]; - [self removeObserverForKeyPath:property]; -} - -- (void)removeActionsForProperty:(NSString *)property { - - NSArray *actions = [self getActionsOfProperty:property]; - if ([actions count] == 0) return; - [_actions removeObjectsInArray:actions]; - [self removeObserverForKeyPath:property]; -} - -- (void)removeActionsForProperties:(NSArray *)properties - target:(id)target - selector:(SEL)selector - onEvent:(SModelEvent)event { - - for (NSString *property in properties) { - [self removeActionsForProperty:property - target:target - selector:selector - onEvent:event]; - } -} - -- (void)removeActionsForProperties:(NSArray *)properties - target:(id)target { - - for (NSString *property in properties) { - [self removeActionsForProperty:property - target:target]; - } -} - -- (void)removeActionsForProperties:(NSArray *)properties { - - for (NSString *property in properties) { - [self removeActionsForProperty:property]; - } -} - -- (void)removeAllActions { - - NSArray *actions = [_actions copy]; - for (SModelAction *action in actions) { - [self removeActionsForProperty:action.keyPath]; - } -} - -- (void)observeValueForKeyPath:(NSString *)keyPath - ofObject:(id)object - change:(NSDictionary *)change - context:(void *)context { - - id oldValue = change[@"old"]; - id newValue = change[@"new"]; - - if (context != SPreadContext) { - return; - } - - SModelEvent event = SModelEventOnChange; - - NSArray *reactions = [self getReactionsOfProperty:keyPath - onEvent:event]; - - for (SModelReaction *reaction in reactions) { - reaction.react(oldValue, newValue); - } - - // Automatic delete action when target become nil. - NSMutableArray *actionsToDelete = [NSMutableArray array]; - - NSArray *actions = [self getActionsOfProperty:keyPath - onEvent:event]; - for (SModelAction *action in actions) { - if (action.target) { - dispatch_async(dispatch_get_main_queue(), ^{ - [NSThread detachNewThreadSelector:action.selector - toTarget:action.target - withObject:self]; - }); - } else { - [actionsToDelete addObject:action]; - } - } - for (SModelAction *action in actionsToDelete) { - [self removeActionsForProperty:action.keyPath]; - } -} - -- (void)fetchInBackground { - - __weak SModel *weakSelf = self; - [SUtils request:[self getSourceUrl] - method:@"GET" - parameters:nil - completionHandler:^(id response, NSError *error) { - [weakSelf initData:[SUtils getDataFrom:response - WithKeyPath:[weakSelf getSourceKeyPath]]]; - }]; -} - -- (void)fetchInBackground:(void (^)(id, NSError *))completion { - - __weak SModel *weakSelf = self; - [SUtils request:[self getSourceUrl] - method:@"GET" - parameters:nil - completionHandler:^(id response, NSError *error) { - NSDictionary *data = [SUtils getDataFrom:response - WithKeyPath:[weakSelf getSourceKeyPath]]; - [weakSelf initData:data]; - if (completion) { - completion(data, error); - } - }]; -} - -- (void)setSourceKeyPath:(NSString *)sourceKeyPath { - - _sourceKeyPath = sourceKeyPath; -} - -- (void)setSourceUrl:(NSString *)sourceUrl { - - _sourceUrl = sourceUrl; -} - -- (NSString *)getSourceKeyPath { - - return _sourceKeyPath; -} - -- (NSString *)getSourceUrl { - - return _sourceUrl; -} - -- (BOOL)isInitiated { - - return _initiated; -} - -- (void)dealloc { - - [self removeAllActions]; - [self removeAllReactions]; -#ifdef DEBUG - NSLog(@"[%@] - Release.", [self class]); -#endif -} - -@end diff --git a/Classes/SPool.h b/Classes/SPool.h index 4855ed6..42abccb 100644 --- a/Classes/SPool.h +++ b/Classes/SPool.h @@ -8,14 +8,12 @@ #import "NSArray+Spread.h" +NS_ASSUME_NONNULL_BEGIN + /** * Spool event. */ typedef NS_ENUM(NSInteger, SPoolEvent){ - /** - * Pool calls event when initial data. - */ - SPoolEventOnInitModel, /** * Pool calls event when add new model. */ @@ -42,6 +40,8 @@ typedef NS_ENUM(NSInteger, SPoolEvent){ */ @property (nonatomic, copy) Class modelClass; +@property (nonatomic) BOOL keep; + /** * Add object to pool. * @@ -60,47 +60,63 @@ typedef NS_ENUM(NSInteger, SPoolEvent){ */ - (NSArray *)addObjects:(NSArray *)objects; +- (NSArray *)replaceByObjects:(NSArray *)objects; + +- (id)insertObject:(NSDictionary *)object + atIndex:(NSUInteger)index; + +- (NSArray *)insertObjects:(NSArray *)objects + atIndexes:(NSIndexSet *)indexes; + +- (void)addModel:(id)model; + +- (void)addModels:(NSArray *)models; + +- (void)replaceByModels:(NSArray *)models; + +- (void)insertModel:(id)model + atIndex:(NSInteger)index; + +- (void)insertModels:(NSArray *)models + atIndexes:(NSIndexSet *)indexes; + /** - * Remove an object to pool. + * Remove an model from pool. * - * @param object Object to remove. + * @param model Model to remove. */ -- (void)removeObject:(id)object; +- (void)removeModel:(id)model; /** - * Remove multi objects in pool. + * Remove multi models in pool. * - * @param objects Array of objects to remove. + * @param models Array of models to remove. */ -- (void)removeObjects:(NSArray *)objects; +- (void)removeModels:(NSArray *)models; /** - * Remove all objects in pool. -*/ -- (void)removeAllObjects; - -/** - * Get all object in from. - * - * @return Array of objects. + * Remove all models in pool. */ -- (NSArray *)allObjects; +- (void)removeAllModels; /** - * Return object match filter. + * Get all model in from. * - * @param filter Filer condition. - * - * @return Array of objects. + * @return Array of models. */ -- (NSArray *)filter:(BOOL (^)(id))filter; +- (NSArray *)allModels; +- (NSArray *)modelSerializer:(NSArray *)objects; +- (NSArray *)diffModels:(NSArray *)models + keys:(NSArray *)keys; +- (NSArray *)diffObjects:(NSArray *)objects + keys:(NSArray *)keys; /** - * Remove object matched filter. + * Remove model matched filter. * * @param filter fitler condition. */ -- (void)removeObjectMatch:(BOOL (^)(id))filter; +- (void)removeModelMatch:(BOOL (^)(id))filter; /** * Reaction when pool change. @@ -133,4 +149,10 @@ typedef NS_ENUM(NSInteger, SPoolEvent){ selector:(SEL)selector onEvent:(SPoolEvent)event; +- (void)triggerForEvent:(SPoolEvent)event; + +@property (nonatomic, strong, nullable) NSDictionary *info; + @end + +NS_ASSUME_NONNULL_END diff --git a/Classes/SPool.m b/Classes/SPool.m index ed28a9f..7186d6b 100644 --- a/Classes/SPool.m +++ b/Classes/SPool.m @@ -7,6 +7,7 @@ // #import "SPool.h" +#import "Mapper.h" @interface SPoolReaction : NSObject @@ -35,7 +36,6 @@ - (BOOL)compareWithTarget:(id)target @implementation SPoolAction - (BOOL)compareWith:(SPoolAction *)action { - return [self compareWithTarget:action.target selector:action.selector event:action.event]; @@ -44,7 +44,6 @@ - (BOOL)compareWith:(SPoolAction *)action { - (BOOL)compareWithTarget:(id)target selector:(SEL)selector event:(SPoolEvent)event { - if ([self.target isEqual:target] && self.selector == selector && self.event == event) { @@ -69,7 +68,6 @@ @implementation SPool { } + (instancetype)sharedInstance { - static dispatch_once_t once; static id sharedInstance; dispatch_once(&once, ^{ @@ -79,7 +77,6 @@ + (instancetype)sharedInstance { } - (instancetype)init { - self = [super init]; if (!self) { return nil; @@ -89,75 +86,176 @@ - (instancetype)init { } - (void)commonInit { - + _keep = NO; _reactions = [NSMutableArray array]; _actions = [NSMutableArray array]; _data = [NSMutableArray array]; } - (NSMutableArray *)reactions { - return _reactions; } +- (NSArray *)modelSerializer:(NSArray *)objects { + NSMutableArray *models = [NSMutableArray array]; + for (NSDictionary *object in objects) { + id model = [[self.modelClass alloc] initWithDictionary:object]; + [models addObject:model]; + } + return models; +} + - (id)addObject:(NSDictionary *)object { - + if (!object) return nil; id model = [[self.modelClass alloc] initWithDictionary:object]; - [_data addObject:model]; - if ([_data count] == 1) { - [self triggerForEvent:SPoolEventOnInitModel]; - } + [self addModel:model]; return model; } - (NSArray *)addObjects:(NSArray *)objects { - - NSMutableArray *dataToAdd = [NSMutableArray array]; - for (NSDictionary *object in objects) { - id model = [[self.modelClass alloc] initWithDictionary:object]; - [dataToAdd addObject:model]; + if ([objects count] == 0) return @[]; + NSArray *dataToAdd = [self modelSerializer:objects]; + [self addModels:dataToAdd]; + return dataToAdd; +} + +- (NSArray *)replaceByObjects:(NSArray *)objects { + NSArray *dataToReplace = [self modelSerializer:objects]; + [self replaceByModels:dataToReplace]; + return dataToReplace; +} + +- (id)insertObject:(NSDictionary *)object + atIndex:(NSUInteger)index { + if (!object) return nil; + id model = [[self.modelClass alloc] initWithDictionary:object]; + [self insertModel:model + atIndex:index]; + return model; +} + +- (NSArray *)insertObjects:(NSArray *)objects + atIndexes:(NSIndexSet *)indexes { + if ([objects count] == 0) return @[]; + NSArray *dataToAdd = [self modelSerializer:objects]; + [self insertModels:dataToAdd + atIndexes:indexes]; + return dataToAdd; +} + +- (void)addModel:(id)model { + NSAssert([[model class] isSubclassOfClass:self.modelClass], @"Model class was not registed."); + if (!model) return; + [_data addObject:model]; + [self triggerForEvent:SPoolEventOnAddModel]; +} + +- (void)addModels:(NSArray *)models { +#ifdef DEBUG + for (id model in models) { + NSAssert([[model class] isSubclassOfClass:self.modelClass], @"Model class was not registed."); } - [_data addObjectsFromArray:dataToAdd]; +#endif + if ([models count] == 0) return; + [_data addObjectsFromArray:models]; [self triggerForEvent:SPoolEventOnAddModel]; - return dataToAdd; } -- (NSArray *)allObjects { - +- (void)replaceByModels:(NSArray *)models { +#ifdef DEBUG + for (id model in models) { + NSAssert([[model class] isSubclassOfClass:self.modelClass], @"Model class was not registed."); + } +#endif + [_data removeAllObjects]; + [_data addObjectsFromArray:models]; + [self triggerForEvent:SPoolEventOnChange]; +} + +- (void)insertModels:(NSArray *)models + atIndexes:(NSIndexSet *)indexes { +#ifdef DEBUG + for (id model in models) { + NSAssert([[model class] isSubclassOfClass:self.modelClass], @"Model class was not registed."); + } +#endif + [_data insertObjects:models + atIndexes:indexes]; + [self triggerForEvent:SPoolEventOnAddModel]; +} + +- (void)insertModel:(id)model + atIndex:(NSInteger)index { + NSAssert([[model class] isSubclassOfClass:self.modelClass], @"Model class was not registed."); + [_data insertObject:model + atIndex:index]; + [self triggerForEvent:SPoolEventOnAddModel]; +} + +- (NSArray *)allModels { return [_data copy]; } -- (void)removeObject:(id)object { - - [_data removeObject:object]; +- (void)removeModel:(id)model { + [_data removeObject:model]; [self triggerForEvent:SPoolEventOnRemoveModel]; } -- (void)removeObjects:(NSArray *)objects { - - [_data removeObjectsInArray:objects]; +- (void)removeModels:(NSArray *)models { + [_data removeObjectsInArray:models]; [self triggerForEvent:SPoolEventOnRemoveModel]; } -- (void)removeAllObjects { - +- (void)removeAllModels { [_data removeAllObjects]; + [self triggerForEvent:SPoolEventOnRemoveModel]; } -- (NSArray *)filter:(BOOL (^)(id))filter { - - NSMutableArray *array = [NSMutableArray array]; - for (id model in [self allObjects]) { - if (filter(model)) { - [array addObject:model]; +- (NSArray *)diffModels:(NSArray *)models + keys:(NSArray *)keys { + NSArray *result = [models filter:^BOOL(Mapper *model) { + for (Mapper *element in self.allModels) { + if ([self compareModel:model + withModel:element + byKeys:keys]) { + return false; + } + } + return true; + }]; + return result; +} + +- (NSArray *)diffObjects:(NSArray *)objects + keys:(NSArray *)keys { + NSArray *models = [self modelSerializer:objects]; + return [self diffModels:models + keys:keys]; +} + +- (BOOL)compareModel:(Mapper *)targetModel + withModel:(Mapper *)model + byKeys:(NSArray *)keys { + for (NSString *key in keys) { + id targetModelValue = [targetModel valueForKey:key]; + id destinationModel = [model valueForKey:key]; + if ([targetModelValue respondsToSelector:@selector(isKindOfClass:)]) { + if ([targetModelValue isKindOfClass:[NSString class]]) { + if (![targetModelValue isEqualToString:destinationModel]) { + return false; + } + } else { + if (targetModelValue != destinationModel) { + return false; + } + } } } - return array; + return true; } - (void)onEvent:(SPoolEvent)event reaction:(void(^)(NSArray *data))reaction { - SPoolReaction *poolReaction = [[SPoolReaction alloc] init]; poolReaction.event = event; poolReaction.reaction = reaction; @@ -167,84 +265,81 @@ - (void)onEvent:(SPoolEvent)event - (void)addTarget:(id)target selector:(SEL)selector onEvent:(SPoolEvent)event { - SPoolAction *poolAction = [[SPoolAction alloc] init]; poolAction.target = target; poolAction.selector = selector; poolAction.event = event; - - for (SPoolAction *action in _actions) { - if ([poolAction compareWith:action] ) { - return; + @synchronized (_actions) { + for (SPoolAction *action in _actions) { + if ([poolAction compareWith:action] ) { + return; + } } + [_actions addObject:poolAction]; } - [_actions addObject:poolAction]; } - (void)triggerForEvent:(SPoolEvent)event { - [self triggerReactionsForEvent:event]; [self triggerTargetForEvent:event]; } - (void)triggerReactionsForEvent:(SPoolEvent)event { - - for (SPoolReaction *reaction in [self reactions]) { - if (reaction.event == SPoolEventOnChange - || reaction.event == event) { - reaction.reaction([_data copy]); + @synchronized (_reactions) { + for (SPoolReaction *reaction in _reactions) { + if (reaction.event == SPoolEventOnChange + || reaction.event == event) { + reaction.reaction([_data copy]); + } } } } - (void)triggerTargetForEvent:(SPoolEvent)event { - NSMutableArray *dataToRemove = [NSMutableArray array]; - for (SPoolAction *action in _actions) { - if (!action.target) { - [dataToRemove addObject:action]; - } else { - if (action.event == SPoolEventOnChange - || action.event == event) { - dispatch_async(dispatch_get_main_queue(), ^{ - [NSThread detachNewThreadSelector:action.selector - toTarget:action.target - withObject:self]; - }); + @synchronized (_actions) { + for (SPoolAction *action in _actions) { + id target = action.target; + if (target) { + if (action.event == SPoolEventOnChange + || action.event == event) { + [[NSOperationQueue mainQueue] addOperationWithBlock:^{ + ((void (*)(id, SEL, id))[target methodForSelector:action.selector])(target, + action.selector, self); + }]; + } + } else { + [dataToRemove addObject:action]; } } + [_actions removeObjectsInArray:dataToRemove]; } - [_actions removeObjectsInArray:dataToRemove]; } - (void)removeTarget:(id)target selector:(SEL)selector onEvent:(SPoolEvent)event { - NSMutableArray *dataToRemove = [NSMutableArray array]; - for (SPoolAction *poolAction in _actions) { - if ([poolAction compareWithTarget:target - selector:selector - event:event]) { - [dataToRemove addObject:poolAction]; + @synchronized (_actions) { + for (SPoolAction *poolAction in _actions) { + if ([poolAction compareWithTarget:target + selector:selector + event:event]) { + [dataToRemove addObject:poolAction]; + } } + [_actions removeObjectsInArray:dataToRemove]; } - [_actions removeObjectsInArray:dataToRemove]; } -- (void)removeObjectMatch:(BOOL (^)(id))filter { - - NSArray *objectToRemove = [self filter:filter]; +- (void)removeModelMatch:(BOOL (^)(id))filter { + NSArray *objectToRemove = [_data filter:filter]; [_data removeObjectsInArray:objectToRemove]; } - (void)dealloc { - [_actions removeAllObjects]; [_reactions removeAllObjects]; -#ifdef DEBUG - NSLog(@"Pool release."); -#endif } @end diff --git a/Classes/SRemoteTask.h b/Classes/SRemoteTask.h index 4a6bcd7..9662c0c 100644 --- a/Classes/SRemoteTask.h +++ b/Classes/SRemoteTask.h @@ -8,6 +8,8 @@ #import +NS_ASSUME_NONNULL_BEGIN + /** * SRemoteTask method description. */ @@ -33,7 +35,7 @@ typedef NS_ENUM(NSInteger, SRemoteTaskMethod){ @interface SRemoteTask : NSObject // Task handler when completed. -@property (nonatomic, copy) void (^handler)(id, NSError *); +@property (nonatomic, copy) void (^handler)(id, NSError * _Nullable); // Task network method. @property (nonatomic) SRemoteTaskMethod method; @@ -44,7 +46,7 @@ typedef NS_ENUM(NSInteger, SRemoteTaskMethod){ * @param executingTask Executing task object in queue. * @return task will dequeue or not. */ -- (BOOL)dequeueCondtion:(SRemoteTask *)executingTask; +- (BOOL)dequeue:(SRemoteTask *)executingTask; /** * Enqueue condition for task object. @@ -52,11 +54,13 @@ typedef NS_ENUM(NSInteger, SRemoteTaskMethod){ * @param penddingTask Pendding task object in queue. * @return task in pending queue will remove or not. */ -- (BOOL)enqueueCondtion:(SRemoteTask *)penddingTask; +- (BOOL)enqueue:(SRemoteTask *)penddingTask; -- (void)addHanlder:(void (^)(id, NSError *))handler; +- (void)addHanlder:(void (^)(id, NSError * _Nullable))handler; - (NSString *)getRequestUrl; - (NSDictionary *)getRequestParameters; - (NSString *)getMethodString; @end + +NS_ASSUME_NONNULL_END diff --git a/Classes/SRemoteTask.m b/Classes/SRemoteTask.m index 54cdd84..4b80506 100644 --- a/Classes/SRemoteTask.m +++ b/Classes/SRemoteTask.m @@ -11,7 +11,6 @@ @implementation SRemoteTask - (instancetype)init { - self =[super init]; if (!self) { return nil; @@ -21,22 +20,18 @@ - (instancetype)init { } - (void)commonInit { - _method = SRemoteTaskMethodPOST; } - (NSString *)getRequestUrl { - return @""; } - (NSDictionary *)getRequestParameters { - return nil; } - (NSString *)getMethodString { - switch (self.method) { case SRemoteTaskMethodGET: return @"GET"; @@ -52,18 +47,15 @@ - (NSString *)getMethodString { } - (void)addHanlder:(void (^)(id, NSError *))handler { - _handler = handler; } -- (BOOL)dequeueCondtion:(SRemoteTask *)executingTask { - +- (BOOL)dequeue:(SRemoteTask *)executingTask { return YES; } -- (BOOL)enqueueCondtion:(SRemoteTask *)penddingTask { - +- (BOOL)enqueue:(SRemoteTask *)penddingTask { return YES; } diff --git a/Classes/SRemoteTaskManager.h b/Classes/SRemoteTaskManager.h index 7543178..9fcb6f7 100644 --- a/Classes/SRemoteTaskManager.h +++ b/Classes/SRemoteTaskManager.h @@ -8,6 +8,8 @@ #import "SRemoteTask.h" +NS_ASSUME_NONNULL_BEGIN + @interface SRemoteTaskManager : NSObject /** @@ -18,3 +20,5 @@ + (void)addTask:(SRemoteTask *)task; @end + +NS_ASSUME_NONNULL_END diff --git a/Classes/SRemoteTaskManager.m b/Classes/SRemoteTaskManager.m index 843e1f1..48a4736 100644 --- a/Classes/SRemoteTaskManager.m +++ b/Classes/SRemoteTaskManager.m @@ -8,7 +8,7 @@ #import "SRemoteTaskManager.h" -#import "SUtils.h" +#import "MapperUtils.h" #import "NSArray+Spread.h" @interface SRemoteTaskManager () @@ -21,7 +21,6 @@ @interface SRemoteTaskManager () @implementation SRemoteTaskManager - (instancetype)init { - self = [super init]; if (!self) { return nil; @@ -31,11 +30,9 @@ - (instancetype)init { } - (void)commonInit { - _pendingTasks = [[NSMutableArray alloc] init]; _executingTasks = [[NSMutableArray alloc] init]; - - NSOperationQueue *queue = [[SUtils sharedInstance] operationQueue]; + NSOperationQueue *queue = [[MapperUtils sharedInstance] operationQueue]; [queue addObserver:self forKeyPath:@"operations" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) @@ -43,7 +40,6 @@ - (void)commonInit { } + (instancetype)sharedInstance { - static dispatch_once_t once; static id sharedInstance; dispatch_once(&once, ^{ @@ -67,76 +63,85 @@ - (void)observeValueForKeyPath:(NSString *)keyPath } - (void)processOperation { - - @synchronized(self) { - - // There are no task in queue. - if ([_pendingTasks count] == 0) { - return; - } - NSOperationQueue *queue = [[SUtils sharedInstance] operationQueue]; - - // Queue is max concurrent. - if ([queue operationCount] >= [queue maxConcurrentOperationCount]) { - return; - } - - for (SRemoteTask *pendingTask in [_pendingTasks copy]) { - if ([self checkDequeueCondtion:pendingTask]) { - [_executingTasks addObject:pendingTask]; - [_pendingTasks removeObject:pendingTask]; - [self processTask:pendingTask]; + @synchronized(_executingTasks) { + @synchronized (_pendingTasks) { + // There are no task in queue. + if ([_pendingTasks count] == 0) { + return; + } + NSOperationQueue *queue = [[MapperUtils sharedInstance] operationQueue]; + + // Queue is max concurrent. + if ([queue operationCount] >= [queue maxConcurrentOperationCount]) { + return; } + NSMutableArray *taskToRemove = [NSMutableArray array]; + for (SRemoteTask *pendingTask in _pendingTasks) { + if ([self checkDequeueCondtion:pendingTask]) { + [_executingTasks addObject:pendingTask]; + [taskToRemove addObject:pendingTask]; + [self processTask:pendingTask]; + } + } + [_pendingTasks removeObjectsInArray:taskToRemove]; } } } - (BOOL)checkDequeueCondtion:(SRemoteTask *)task { - - if ([_executingTasks count] == 0) { - return YES; - } - NSArray *executingTasksWithKind = [[_executingTasks copy] filter:^BOOL(id element) { - return [task isKindOfClass:[element class]]; - }]; - if ([executingTasksWithKind count] == 0) { - return YES; - } - NSArray *tasks = [executingTasksWithKind filter:^BOOL(SRemoteTask *element) { - return ![task dequeueCondtion:element]; - }]; - if ([tasks count] == 0) { - return YES; + @synchronized (_executingTasks) { + if ([_executingTasks count] == 0) { + return YES; + } + NSArray *executingTasksWithKind = [_executingTasks filter:^BOOL(id element) { + return [task isKindOfClass:[element class]]; + }]; + if ([executingTasksWithKind count] == 0) { + return YES; + } + NSArray *tasks = [executingTasksWithKind filter:^BOOL(SRemoteTask *element) { + return ![task dequeue:element]; + }]; + if ([tasks count] == 0) { + return YES; + } + return NO; } - return NO; } + (void)addTask:(SRemoteTask *)task { - + NSAssert([task.class isSubclassOfClass:[SRemoteTask class]], @"Task must be SRemoteTask or sub class of SRemoteTask."); + if (![task.class isSubclassOfClass:[SRemoteTask class]]) { + return; + } NSMutableArray *pendingTasks = [[self sharedInstance] pendingTasks]; - NSArray *tasksToRemove = [[[pendingTasks copy] - filter:^BOOL(id element) { - return [task isKindOfClass:[element class]]; - }] - filter:^BOOL(id element) { - return ![task enqueueCondtion:element]; - }]; - [pendingTasks removeObjectsInArray:tasksToRemove]; - [pendingTasks addObject:task]; - [[self sharedInstance] processOperation]; + @synchronized (pendingTasks) { + NSArray *tasksToRemove = [[pendingTasks + filter:^BOOL(id element) { + return [task isKindOfClass:[element class]]; + }] + filter:^BOOL(id element) { + return ![task enqueue:element]; + }]; + [pendingTasks removeObjectsInArray:tasksToRemove]; + [pendingTasks addObject:task]; + [[self sharedInstance] processOperation]; + } } - (void)processTask:(SRemoteTask *)task { - - [SUtils request:[task getRequestUrl] - method:[task getMethodString] - parameters:[task getRequestParameters] - completionHandler:^(id response, NSError *error) { - if (task.handler) { - task.handler(response, error); - } - [_executingTasks removeObject:task]; - }]; + [MapperUtils request:[task getRequestUrl] + method:[task getMethodString] + parameters:[task getRequestParameters] + headers: nil + completionHandler:^(id response, NSError *error) { + @synchronized (_executingTasks) { + if (task.handler) { + task.handler(response, error); + } + [_executingTasks removeObject:task]; + } + }]; } @end diff --git a/Classes/Spread.h b/Classes/Spread.h index 90a0d56..022fd69 100644 --- a/Classes/Spread.h +++ b/Classes/Spread.h @@ -6,9 +6,11 @@ // Copyright (c) 2015 Katana. All rights reserved. // -#import "SModel.h" +#import "Mapper.h" #import "SPool.h" +NS_ASSUME_NONNULL_BEGIN + @interface Spread : NSObject /** @@ -18,14 +20,22 @@ */ + (instancetype)sharedInstance; ++ (void)setNetworkHeader:(NSDictionary *)headers; + ++ (NSDictionary *)getNetworkHeaders; + /** * Register class for pools. * * @param modelClass Class for coder. * @param identifiers Array list of pools identifier. */ -+ (void)registerClass:(Class)modelClass - forPoolIdentifier:(NSString *)identifier; ++ (SPool *)registerClass:(Class)modelClass + forPoolIdentifier:(NSString *)identifier; + ++ (SPool *)registerClass:(Class)modelClass + forPoolIdentifier:(NSString *)identifier + keep:(BOOL)keep; /** * Remove a pool and class register from memory. @@ -73,7 +83,7 @@ * * @return Pool object. */ -+ (SPool *)getPool:(NSString *)identifier; ++ (nullable SPool *)getPool:(NSString *)identifier; /** * Add an object to pool. @@ -83,7 +93,7 @@ * * @return Spread model. */ -+ (SModel *)addObject:(NSDictionary *)object ++ (Mapper *)addObject:(NSDictionary *)object toPool:(NSString *)identifier; /** @@ -97,14 +107,36 @@ + (NSArray *)addObjects:(NSArray *)objects toPool:(NSString *)identifier; ++ (Mapper *)insertObject:(NSDictionary *)object + atIndex:(NSInteger)index + toPool:(NSString *)identifier; + ++ (NSArray *)insertObjects:(NSArray *)objects + atIndexes:(NSIndexSet *)indexes + toPool:(NSString *)identifier; + ++ (void)addModel:(id)model + toPool:(NSString *)identifier; + ++ (void)addModels:(NSArray *)models + toPool:(NSString *)identifier; + ++ (void)insertModel:(id)model + atIndex:(NSInteger)index + toPool:(NSString *)identifier; + ++ (void)insertModels:(NSArray *)models + atIndexes:(NSIndexSet *)indexes + toPool:(NSString *)identifier; + /** * Remove an object from pool with identifier. * * @param object Object to remove. * @param identifier Pool identifer. */ -+ (void)removeObject:(id)object - fromPool:(NSString *)identifier; ++ (void)removeModel:(id)model + fromPool:(NSString *)identifier; /** * Remove multi object in pool. @@ -112,8 +144,8 @@ * @param objects Array of objects. * @param identifier Pool identifier. */ -+ (void)removeObjects:(NSArray *)objects - fromPool:(NSString *)identifier; ++ (void)removeModels:(NSArray *)models + fromPool:(NSString *)identifier; /** * Trigger event and send event to every pool had registed. @@ -131,4 +163,8 @@ */ + (void)setMaxConcurrentOperationCount:(NSInteger)maxConcurrentOperationCount; ++ (void)setCapacity:(NSInteger)capacity; + @end + +NS_ASSUME_NONNULL_END diff --git a/Classes/Spread.m b/Classes/Spread.m index 9e0b624..296166c 100644 --- a/Classes/Spread.m +++ b/Classes/Spread.m @@ -6,9 +6,11 @@ // Copyright (c) 2015 Katana. All rights reserved. // +#define KEEP NO + #import "Spread.h" -#import "SUtils.h" +#import "MapperUtils.h" @interface SpreadAction: NSObject @@ -26,13 +28,14 @@ @interface Spread() @property (nonatomic, strong) NSMutableArray *pools; @property (nonatomic, strong) NSMutableArray *poolActions; +@property (nonatomic, strong) NSDictionary *networkHeader; +@property (nonatomic) NSInteger capacity; @end @implementation Spread + (instancetype)sharedInstance { - static dispatch_once_t once; static id sharedInstance; dispatch_once(&once, ^{ @@ -41,8 +44,15 @@ + (instancetype)sharedInstance { return sharedInstance; } ++ (void)setNetworkHeader:(NSDictionary *)headers { + [[self sharedInstance] setNetworkHeader:headers]; +} + ++ (NSDictionary *)getNetworkHeaders { + return [[self sharedInstance] networkHeader]; +} + - (instancetype)init { - self = [super init]; if (!self) { return nil; @@ -52,59 +62,84 @@ - (instancetype)init { } - (void)commonInit { - + _capacity = INT_MAX; _pools = [NSMutableArray array]; _poolActions = [NSMutableArray array]; } +- (void)addPool:(SPool *)pool { + @synchronized(_pools) { + if ([_pools count] > self.capacity - 1) { + for (SPool *spool in _pools) { + if (!spool.keep) { + [_pools removeObject:spool]; + break; + } + } + } + [[self pools] addObject:pool]; + } +} + + (SPool *)getPool:(NSString *)identifier { - - for (SPool *pool in [[self sharedInstance] pools]) { - if ([pool.identifier isEqualToString:identifier]) { - return pool; + NSArray *pools = [[self sharedInstance] pools]; + @synchronized(pools) { + for (SPool *pool in pools) { + if ([pool.identifier isEqualToString:identifier]) { + return pool; + } } } return nil; } -+ (void)registerClass:(Class)modelClass - forPoolIdentifier:(NSString *)identifier { - ++ (SPool *)registerClass:(Class)modelClass + forPoolIdentifier:(NSString *)identifier { + return [self registerClass:modelClass + forPoolIdentifier:identifier + keep:KEEP]; +} + ++ (SPool *)registerClass:(Class)modelClass + forPoolIdentifier:(NSString *)identifier + keep:(BOOL)keep { SPool *pool = [self getPool:identifier]; - @synchronized(self) { + @synchronized([[self sharedInstance] pools]) { if (!pool) { pool = [[SPool alloc] init]; pool.identifier = identifier; pool.modelClass = modelClass; - [[[self sharedInstance] pools] addObject:pool]; + pool.keep = keep; + [[self sharedInstance] addPool:pool]; + return pool; } else { - NSAssert([modelClass isSubclassOfClass:[SModel class]], + NSAssert([modelClass isSubclassOfClass:[Mapper class]], @"Model register must be SModel or subclass of SModel."); - NSAssert([pool allObjects].count == 0 || pool.modelClass == modelClass, + NSAssert([pool allModels].count == 0 || pool.modelClass == modelClass, @"Pool contains model and has been registered with another model class."); } + return pool; } } + (void)removePoolWithIdentifier:(NSString *)identifier { - - // Remove pool action. + NSMutableArray *actions = [[self sharedInstance] poolActions]; NSMutableArray *actionToRemove = [NSMutableArray array]; - for (SpreadAction *action in [[self sharedInstance] poolActions]) { - if ([action.poolIdentifier isEqualToString:identifier]) { - [actionToRemove addObject:action]; + @synchronized (actions) { + for (SpreadAction *action in actions) { + if ([action.poolIdentifier isEqualToString:identifier]) { + [actionToRemove addObject:action]; + } } + [actions removeObjectsInArray:actionToRemove]; + // Remove pool. + SPool *pool = [self getPool:identifier]; + [[[self sharedInstance] pools] removeObject:pool]; } - [[[self sharedInstance] poolActions] removeObjectsInArray:actionToRemove]; - - // Remove pool. - SPool *pool = [self getPool:identifier]; - [[[self sharedInstance] pools] removeObject:pool]; } + (NSInteger)countIndentifer:(NSString *)identifier inArray:(NSArray *)array { - NSInteger count = 0; for (NSString *string in array) { if ([identifier isEqualToString:string]) { @@ -117,7 +152,6 @@ + (NSInteger)countIndentifer:(NSString *)identifier inArray:(NSArray *)array { + (void)registerEvent:(NSString *)event poolIdentifiers:(NSArray *)poolIdentifiers action:(void (^)(id, SPool *))action { - for (NSString *poolIdentifier in poolIdentifiers) { #ifdef DEBUG if ([self countIndentifer:poolIdentifier inArray:poolIdentifiers] > 1) { @@ -134,79 +168,132 @@ + (void)registerEvent:(NSString *)event + (void)removeEvent:(NSString *)event poolIdentifiers:(NSArray *)poolIdentifiers { - + NSMutableArray *actions = [[self sharedInstance] poolActions]; NSMutableArray *actionsToDelete = [NSMutableArray array]; - for (SpreadAction *action in [[self sharedInstance] poolActions]) { - if ([action.event isEqualToString:event] - && [self countIndentifer:action.poolIdentifier inArray:poolIdentifiers] > 0) { - [actionsToDelete addObject:action]; + @synchronized (actions) { + for (SpreadAction *action in actions) { + if ([action.event isEqualToString:event] + && [self countIndentifer:action.poolIdentifier inArray:poolIdentifiers] > 0) { + [actionsToDelete addObject:action]; + } } + [actions removeObjectsInArray:actionsToDelete]; } - [[[self sharedInstance] poolActions] removeObjectsInArray:actionsToDelete]; } + (void)removeEvent:(NSString *)event { - + NSMutableArray *actions = [[self sharedInstance] poolActions]; NSMutableArray *actionsToDelete = [NSMutableArray array]; - for (SpreadAction *action in [[self sharedInstance] poolActions]) { - if ([action.event isEqualToString:event]) { - [actionsToDelete addObject:action]; + @synchronized (actions) { + for (SpreadAction *action in actions) { + if ([action.event isEqualToString:event]) { + [actionsToDelete addObject:action]; + } } + [actions removeObjectsInArray:actionsToDelete]; } - [[[self sharedInstance] poolActions] removeObjectsInArray:actionsToDelete]; } + (void)removeAllEvent { - [[[self sharedInstance] poolActions] removeAllObjects]; } -+ (SModel *)addObject:(NSDictionary *)object ++ (Mapper *)addObject:(NSDictionary *)object toPool:(NSString *)identifier { - SPool *pool = [self getPool:identifier]; return [pool addObject:object]; } + (NSArray *)addObjects:(NSArray *)objects toPool:(NSString *)identifier { - SPool *pool = [self getPool:identifier]; return [pool addObjects:objects]; } -+ (void)removeObject:(id)object - fromPool:(NSString *)identifier { - ++ (Mapper *)insertObject:(NSDictionary *)object + atIndex:(NSInteger)index + toPool:(NSString *)identifier { + SPool *pool = [self getPool:identifier]; + return [pool insertObject:object + atIndex:index]; +} + ++ (NSArray *)insertObjects:(NSArray *)objects + atIndexes:(NSIndexSet *)indexes + toPool:(NSString *)identifier { + SPool *pool = [self getPool:identifier]; + return [pool insertObjects:objects + atIndexes:indexes]; +} + ++ (void)addModels:(NSArray *)models + toPool:(NSString *)identifier { + SPool *pool = [self getPool:identifier]; + [pool addModels:models]; +} + ++ (void)addModel:(id)model + toPool:(NSString *)identifier { + SPool *pool = [self getPool:identifier]; + [pool addModel:model]; +} + ++ (void)insertModel:(id)model + atIndex:(NSInteger)index + toPool:(NSString *)identifier { + SPool *pool = [self getPool:identifier]; + [pool insertModel:model + atIndex:index]; +} + ++ (void)insertModels:(NSArray *)models + atIndexes:(NSIndexSet *)indexes + toPool:(NSString *)identifier { + SPool *pool = [self getPool:identifier]; + [pool insertModels:models + atIndexes:indexes]; +} + ++ (void)removeModel:(id)model + fromPool:(NSString *)identifier { SPool *pool = [self getPool:identifier]; if (pool) { - [pool removeObject:object]; + [pool removeModel:model]; } } -+ (void)removeObjects:(NSArray *)objects - fromPool:(NSString *)identifier { - ++ (void)removeModels:(NSArray *)models + fromPool:(NSString *)identifier { SPool *pool = [self getPool:identifier]; - [pool removeObjects:objects]; + [pool removeModels:models]; } + (void)outEvent:(NSString *)event value:(NSDictionary *)value { - - for (SpreadAction *poolAction in [[self sharedInstance] poolActions]) { - if ([poolAction.event isEqualToString:event]) { - SPool *pool = [self getPool:poolAction.poolIdentifier]; - poolAction.action(value, pool); + NSMutableArray *actions = [[self sharedInstance] poolActions]; + @synchronized (actions) { + for (SpreadAction *poolAction in actions) { + if ([poolAction.event isEqualToString:event]) { + SPool *pool = [self getPool:poolAction.poolIdentifier]; + if (pool) { + poolAction.action(value, pool); + } else { + [[[self sharedInstance] poolActions] removeObject:poolAction]; + } + } } } } + (void)setMaxConcurrentOperationCount:(NSInteger)maxConcurrentOperationCount { - - NSAssert(maxConcurrentOperationCount <= 0, @"Max concurrent must be geater than zero."); - NSOperationQueue *sharedOperationQueue = [[SUtils sharedInstance] operationQueue]; + NSAssert(maxConcurrentOperationCount >= 0, @"Max concurrent must be geater than zero."); + NSOperationQueue *sharedOperationQueue = [[MapperUtils sharedInstance] operationQueue]; [sharedOperationQueue setMaxConcurrentOperationCount:maxConcurrentOperationCount]; } ++ (void)setCapacity:(NSInteger)capacity { + NSAssert(capacity >= 0, @"Max capacity must be geater than zero."); + [[self sharedInstance] setCapacity:capacity]; +} + @end diff --git a/Default-568h@2x.png b/Default-568h@2x.png new file mode 100644 index 0000000..0891b7a Binary files /dev/null and b/Default-568h@2x.png differ diff --git a/README.md b/README.md index d99e516..32dded6 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,5 @@ [![Build Status](https://travis-ci.org/huyphams/Spread.svg)](https://travis-ci.org/huyphams/Spread)[![CocoaPods Version](https://cocoapod-badges.herokuapp.com/v/Spread/badge.png)](http://cocoapods.org/?q=spread) - Spread is a data flow control. It changes the way you manage your data. ## Features @@ -18,7 +17,7 @@ Spread is a data flow control. It changes the way you manage your data. ```ruby -pod "Spread", "~> 1.1.0" +pod "Spread", "~> 1.2.1" ``` @@ -34,12 +33,11 @@ pod "Spread", "~> 1.1.0" ``` -#### Create a class sub class SModel +#### Create a class sub class Mapper ```swift -class Model: SModel { - +class Model: Mapper { dynamic var objectId: String! dynamic var name: String! } @@ -49,7 +47,7 @@ class Model: SModel { ```swift - Spread.registerClass(Model.classForCoder(), forPoolIdentifier:"PoolIdentifier") +Spread.registerClass(Model.classForCoder(), forPoolIdentifier:"PoolIdentifier") ``` @@ -79,7 +77,7 @@ Spread.registerEvent("TheEvent", let model = Spread.addObject(["name": "Some name", "objectId": "123"], toPool: self.pool1Identifier) -model.property("name", onEvent: SModelEvent.OnChange) { (oldValue, newValue) -> Void in +model.property("name", onEvent: .OnChange) { (oldValue, newValue) -> Void in aTextField.text = newValue as String } @@ -89,8 +87,8 @@ model.property("name", onEvent: SModelEvent.OnChange) { (oldValue, newValue) -> ```swift - Spread.outEvent("TheEvent", - value: ["name": "Change the name", "objectId": "123"]) +Spread.outEvent("TheEvent", + value: ["name": "Change the name", "objectId": "123"]) ``` diff --git a/Spread-Bridging-Header.h b/Spread-Bridging-Header.h index 0ba1b29..4ff9179 100644 --- a/Spread-Bridging-Header.h +++ b/Spread-Bridging-Header.h @@ -3,4 +3,5 @@ // #import "Spread.h" -#import "SRemoteTaskManager.h" \ No newline at end of file +#import "SRemoteTaskManager.h" +#import "Milk.h" \ No newline at end of file diff --git a/Spread.podspec b/Spread.podspec index 6859bb8..bd5db80 100644 --- a/Spread.podspec +++ b/Spread.podspec @@ -1,12 +1,12 @@ Pod::Spec.new do |s| s.name = "Spread" - s.version = "1.1.0" + s.version = "1.2.1" s.summary = "Spread is a data flow control, inspire from: When the shit hit the fan, it will be spread all over." - s.homepage = "http://facebook.com/huyphams" + s.homepage = "http://huypham.me" s.license = "MIT" s.author = { "Huy Pham" => "duchuykun@gmail.com" } - s.social_media_url = "https://facebook.com/huyphams" + s.social_media_url = "https://www.instagram.com/huyphams" s.platform = :ios, "7.0" s.source = { :git => "https://github.com/huyphams/Spread.git", :tag => "#{s.version}" } s.source_files = "Classes/*.{h,m}" diff --git a/Spread.xcodeproj/project.pbxproj b/Spread.xcodeproj/project.pbxproj index e72f104..4eb5da6 100644 --- a/Spread.xcodeproj/project.pbxproj +++ b/Spread.xcodeproj/project.pbxproj @@ -12,16 +12,19 @@ 11004B1D1AC4252100013372 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 11004B1C1AC4252100013372 /* Images.xcassets */; }; 11004B391AC4255300013372 /* Spread.m in Sources */ = {isa = PBXBuildFile; fileRef = 11004B381AC4255300013372 /* Spread.m */; }; 11004B3C1AC42FBC00013372 /* SPool.m in Sources */ = {isa = PBXBuildFile; fileRef = 11004B3B1AC42FBC00013372 /* SPool.m */; }; - 11004B3F1AC43D8200013372 /* SModel.m in Sources */ = {isa = PBXBuildFile; fileRef = 11004B3E1AC43D8200013372 /* SModel.m */; }; 11004B421AC45CF500013372 /* Networking.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11004B411AC45CF500013372 /* Networking.swift */; }; 11004B451AC4608700013372 /* Carrot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11004B441AC4608700013372 /* Carrot.swift */; }; + 1109151C1B88FA63006CC848 /* Milk.m in Sources */ = {isa = PBXBuildFile; fileRef = 1109151B1B88FA63006CC848 /* Milk.m */; }; 110E2C011ADD8358004F5764 /* SRemoteTaskManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 110E2C001ADD8358004F5764 /* SRemoteTaskManager.m */; }; 110E2C041ADD83F8004F5764 /* SRemoteTask.m in Sources */ = {isa = PBXBuildFile; fileRef = 110E2C031ADD83F8004F5764 /* SRemoteTask.m */; }; 110E2C091ADDA8FB004F5764 /* Task.swift in Sources */ = {isa = PBXBuildFile; fileRef = 110E2C081ADDA8FB004F5764 /* Task.swift */; }; 110E2C0F1ADE08BB004F5764 /* OtherTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = 110E2C0E1ADE08BB004F5764 /* OtherTask.swift */; }; 1147AC511AC72C30009C8BF2 /* SpreadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11004B2B1AC4252100013372 /* SpreadTests.swift */; }; - 1170D2111AD6D3E900924E72 /* SUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = 1170D2101AD6D3E900924E72 /* SUtils.m */; }; 11B1E1981AD22E9100765C35 /* NSArray+Spread.m in Sources */ = {isa = PBXBuildFile; fileRef = 11B1E1971AD22E9100765C35 /* NSArray+Spread.m */; }; + E597CBC21E25F0D900E5C045 /* Decoder.m in Sources */ = {isa = PBXBuildFile; fileRef = E597CBBD1E25F0D900E5C045 /* Decoder.m */; }; + E597CBC31E25F0D900E5C045 /* Mapper.m in Sources */ = {isa = PBXBuildFile; fileRef = E597CBBF1E25F0D900E5C045 /* Mapper.m */; }; + E597CBC41E25F0D900E5C045 /* MapperUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = E597CBC11E25F0D900E5C045 /* MapperUtils.m */; }; + E599A3091DBB179A00DB48DE /* Default-568h@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = E599A3081DBB179A00DB48DE /* Default-568h@2x.png */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -48,20 +51,25 @@ 11004B381AC4255300013372 /* Spread.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Spread.m; path = Classes/Spread.m; sourceTree = ""; }; 11004B3A1AC42FBC00013372 /* SPool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SPool.h; path = Classes/SPool.h; sourceTree = ""; }; 11004B3B1AC42FBC00013372 /* SPool.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SPool.m; path = Classes/SPool.m; sourceTree = ""; }; - 11004B3D1AC43D8200013372 /* SModel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SModel.h; path = Classes/SModel.h; sourceTree = ""; }; - 11004B3E1AC43D8200013372 /* SModel.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SModel.m; path = Classes/SModel.m; sourceTree = ""; }; 11004B411AC45CF500013372 /* Networking.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Networking.swift; path = Spread/Utils/Networking.swift; sourceTree = ""; }; 11004B441AC4608700013372 /* Carrot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Carrot.swift; path = Models/Carrot.swift; sourceTree = ""; }; + 1109151A1B88FA63006CC848 /* Milk.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Milk.h; path = Models/Milk.h; sourceTree = ""; }; + 1109151B1B88FA63006CC848 /* Milk.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Milk.m; path = Models/Milk.m; sourceTree = ""; }; 110E2BFF1ADD8358004F5764 /* SRemoteTaskManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SRemoteTaskManager.h; path = Classes/SRemoteTaskManager.h; sourceTree = ""; }; 110E2C001ADD8358004F5764 /* SRemoteTaskManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SRemoteTaskManager.m; path = Classes/SRemoteTaskManager.m; sourceTree = ""; }; 110E2C021ADD83F8004F5764 /* SRemoteTask.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SRemoteTask.h; path = Classes/SRemoteTask.h; sourceTree = ""; }; 110E2C031ADD83F8004F5764 /* SRemoteTask.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SRemoteTask.m; path = Classes/SRemoteTask.m; sourceTree = ""; }; 110E2C081ADDA8FB004F5764 /* Task.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Task.swift; path = Tasks/Task.swift; sourceTree = ""; }; 110E2C0E1ADE08BB004F5764 /* OtherTask.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = OtherTask.swift; path = Tasks/OtherTask.swift; sourceTree = ""; }; - 1170D20F1AD6D3E900924E72 /* SUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SUtils.h; path = Classes/SUtils.h; sourceTree = ""; }; - 1170D2101AD6D3E900924E72 /* SUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SUtils.m; path = Classes/SUtils.m; sourceTree = ""; }; 11B1E1961AD22E9100765C35 /* NSArray+Spread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSArray+Spread.h"; path = "Classes/NSArray+Spread.h"; sourceTree = ""; }; 11B1E1971AD22E9100765C35 /* NSArray+Spread.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSArray+Spread.m"; path = "Classes/NSArray+Spread.m"; sourceTree = ""; }; + E597CBBC1E25F0D900E5C045 /* Decoder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Decoder.h; path = Classes/Decoder.h; sourceTree = ""; }; + E597CBBD1E25F0D900E5C045 /* Decoder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Decoder.m; path = Classes/Decoder.m; sourceTree = ""; }; + E597CBBE1E25F0D900E5C045 /* Mapper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Mapper.h; path = Classes/Mapper.h; sourceTree = ""; }; + E597CBBF1E25F0D900E5C045 /* Mapper.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Mapper.m; path = Classes/Mapper.m; sourceTree = ""; }; + E597CBC01E25F0D900E5C045 /* MapperUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = MapperUtils.h; path = Classes/MapperUtils.h; sourceTree = ""; }; + E597CBC11E25F0D900E5C045 /* MapperUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = MapperUtils.m; path = Classes/MapperUtils.m; sourceTree = ""; }; + E599A3081DBB179A00DB48DE /* Default-568h@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "Default-568h@2x.png"; path = "../Default-568h@2x.png"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -118,6 +126,7 @@ 11004B131AC4252100013372 /* Supporting Files */ = { isa = PBXGroup; children = ( + E599A3081DBB179A00DB48DE /* Default-568h@2x.png */, 11004B361AC4255200013372 /* Spread-Bridging-Header.h */, 11004B141AC4252100013372 /* Info.plist */, ); @@ -144,16 +153,18 @@ 11004B351AC4252F00013372 /* Classes */ = { isa = PBXGroup; children = ( + E597CBBC1E25F0D900E5C045 /* Decoder.h */, + E597CBBD1E25F0D900E5C045 /* Decoder.m */, + E597CBBE1E25F0D900E5C045 /* Mapper.h */, + E597CBBF1E25F0D900E5C045 /* Mapper.m */, + E597CBC01E25F0D900E5C045 /* MapperUtils.h */, + E597CBC11E25F0D900E5C045 /* MapperUtils.m */, 11004B371AC4255300013372 /* Spread.h */, 11004B381AC4255300013372 /* Spread.m */, 11004B3A1AC42FBC00013372 /* SPool.h */, 11004B3B1AC42FBC00013372 /* SPool.m */, - 11004B3D1AC43D8200013372 /* SModel.h */, - 11004B3E1AC43D8200013372 /* SModel.m */, 11B1E1961AD22E9100765C35 /* NSArray+Spread.h */, 11B1E1971AD22E9100765C35 /* NSArray+Spread.m */, - 1170D20F1AD6D3E900924E72 /* SUtils.h */, - 1170D2101AD6D3E900924E72 /* SUtils.m */, 110E2BFF1ADD8358004F5764 /* SRemoteTaskManager.h */, 110E2C001ADD8358004F5764 /* SRemoteTaskManager.m */, 110E2C021ADD83F8004F5764 /* SRemoteTask.h */, @@ -175,6 +186,8 @@ isa = PBXGroup; children = ( 11004B441AC4608700013372 /* Carrot.swift */, + 1109151A1B88FA63006CC848 /* Milk.h */, + 1109151B1B88FA63006CC848 /* Milk.m */, ); name = Models; sourceTree = ""; @@ -232,14 +245,19 @@ 11004B081AC4252100013372 /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 0620; + LastSwiftMigration = 0710; + LastSwiftUpdateCheck = 0710; + LastUpgradeCheck = 0800; ORGANIZATIONNAME = Katana; TargetAttributes = { 11004B0F1AC4252100013372 = { CreatedOnToolsVersion = 6.2; + DevelopmentTeam = 3X57WP8E8V; + LastSwiftMigration = 0800; }; 11004B241AC4252100013372 = { CreatedOnToolsVersion = 6.2; + LastSwiftMigration = 0800; TestTargetID = 11004B0F1AC4252100013372; }; }; @@ -269,6 +287,7 @@ buildActionMask = 2147483647; files = ( 11004B1D1AC4252100013372 /* Images.xcassets in Resources */, + E599A3091DBB179A00DB48DE /* Default-568h@2x.png in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -286,10 +305,12 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 1170D2111AD6D3E900924E72 /* SUtils.m in Sources */, + E597CBC41E25F0D900E5C045 /* MapperUtils.m in Sources */, + E597CBC31E25F0D900E5C045 /* Mapper.m in Sources */, 11004B181AC4252100013372 /* ViewController.swift in Sources */, - 11004B3F1AC43D8200013372 /* SModel.m in Sources */, + E597CBC21E25F0D900E5C045 /* Decoder.m in Sources */, 110E2C041ADD83F8004F5764 /* SRemoteTask.m in Sources */, + 1109151C1B88FA63006CC848 /* Milk.m in Sources */, 110E2C091ADDA8FB004F5764 /* Task.swift in Sources */, 11004B161AC4252100013372 /* AppDelegate.swift in Sources */, 110E2C011ADD8358004F5764 /* SRemoteTaskManager.m in Sources */, @@ -334,15 +355,19 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", @@ -376,8 +401,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -385,6 +412,7 @@ ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; @@ -394,6 +422,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 8.2; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; VALIDATE_PRODUCT = YES; }; name = Release; @@ -401,29 +430,37 @@ 11004B301AC4252100013372 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + DEVELOPMENT_TEAM = 3X57WP8E8V; INFOPLIST_FILE = Spread/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "katana.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; SWIFT_OBJC_BRIDGING_HEADER = "Spread-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 3.0; }; name = Debug; }; 11004B311AC4252100013372 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + DEVELOPMENT_TEAM = 3X57WP8E8V; INFOPLIST_FILE = Spread/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "katana.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE = ""; SWIFT_OBJC_BRIDGING_HEADER = "Spread-Bridging-Header.h"; + SWIFT_VERSION = 3.0; }; name = Release; }; @@ -431,10 +468,7 @@ isa = XCBuildConfiguration; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; - FRAMEWORK_SEARCH_PATHS = ( - "$(SDKROOT)/Developer/Library/Frameworks", - "$(inherited)", - ); + FRAMEWORK_SEARCH_PATHS = "$(inherited)"; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", @@ -445,7 +479,9 @@ ); INFOPLIST_FILE = SpreadTests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "katana.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Spread.app/Spread"; }; name = Debug; @@ -454,17 +490,16 @@ isa = XCBuildConfiguration; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; - FRAMEWORK_SEARCH_PATHS = ( - "$(SDKROOT)/Developer/Library/Frameworks", - "$(inherited)", - ); + FRAMEWORK_SEARCH_PATHS = "$(inherited)"; HEADER_SEARCH_PATHS = ( "$(inherited)", /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include, ); INFOPLIST_FILE = SpreadTests/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = "katana.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Spread.app/Spread"; }; name = Release; diff --git a/Spread.xcodeproj/xcshareddata/xcschemes/Spread.xcscheme b/Spread.xcodeproj/xcshareddata/xcschemes/Spread.xcscheme index 82d70a9..cf3a358 100644 --- a/Spread.xcodeproj/xcshareddata/xcschemes/Spread.xcscheme +++ b/Spread.xcodeproj/xcshareddata/xcschemes/Spread.xcscheme @@ -1,6 +1,6 @@ + shouldUseLaunchSchemeArgsEnv = "YES"> @@ -62,15 +62,18 @@ ReferencedContainer = "container:Spread.xcodeproj"> + + @@ -82,14 +85,21 @@ ReferencedContainer = "container:Spread.xcodeproj"> + + + + diff --git a/Spread/AppDelegate.swift b/Spread/AppDelegate.swift index 1053777..551efef 100644 --- a/Spread/AppDelegate.swift +++ b/Spread/AppDelegate.swift @@ -13,12 +13,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - - func application(application: UIApplication, didFinishLaunchingWithOptions - launchOptions: [NSObject: AnyObject]?) -> Bool { - + func application(_ application: UIApplication, didFinishLaunchingWithOptions + launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let rootViewController = ViewController() - let window = UIWindow(frame: UIScreen.mainScreen().bounds) + let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = rootViewController self.window = window diff --git a/Spread/Images.xcassets/AppIcon.appiconset/Contents.json b/Spread/Images.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index 118c98f..0000000 --- a/Spread/Images.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "images" : [ - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "3x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Spread/Images.xcassets/Contents.json b/Spread/Images.xcassets/Contents.json new file mode 100644 index 0000000..da4a164 --- /dev/null +++ b/Spread/Images.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Spread/Images.xcassets/LaunchImage.launchimage/Contents.json b/Spread/Images.xcassets/LaunchImage.launchimage/Contents.json deleted file mode 100644 index e37b649..0000000 --- a/Spread/Images.xcassets/LaunchImage.launchimage/Contents.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "images" : [ - { - "orientation" : "portrait", - "idiom" : "iphone", - "minimum-system-version" : "7.0", - "scale" : "2x" - }, - { - "orientation" : "portrait", - "idiom" : "iphone", - "minimum-system-version" : "7.0", - "subtype" : "retina4", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Spread/Info.plist b/Spread/Info.plist index 024f0d8..e1888f5 100644 --- a/Spread/Info.plist +++ b/Spread/Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier - katana.$(PRODUCT_NAME:rfc1034identifier) + $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName @@ -26,11 +26,11 @@ armv7 + UIRequiresFullScreen + UISupportedInterfaceOrientations UIInterfaceOrientationPortrait - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight diff --git a/Spread/Models/Carrot.swift b/Spread/Models/Carrot.swift index 305e34e..3b2a806 100644 --- a/Spread/Models/Carrot.swift +++ b/Spread/Models/Carrot.swift @@ -6,10 +6,8 @@ // Copyright (c) 2015 Katana. All rights reserved. // -import UIKit - -class Carrot: SModel { - - dynamic var objectId: String! - dynamic var name: String! +class Carrot: Mapper { + dynamic var objectId: NSString! + dynamic var name: NSString! + dynamic var milk: Milk! } diff --git a/Spread/Models/Milk.h b/Spread/Models/Milk.h new file mode 100644 index 0000000..ca39bb7 --- /dev/null +++ b/Spread/Models/Milk.h @@ -0,0 +1,28 @@ +// +// Milk.h +// Spread +// +// Created by Huy Pham on 8/23/15. +// Copyright (c) 2015 Katana. All rights reserved. +// + +#import +#import "Mapper.h" + +@interface Milk : Mapper + +@property (nonatomic, copy) NSString *__id; +@property (nonatomic) NSInteger number1; +@property (nonatomic) NSInteger number2; +@property (nonatomic) NSUInteger number3; + +@property (nonatomic) BOOL status1; +@property (nonatomic) bool status2; +@property (nonatomic) Boolean status3; + +@property (nonatomic) CGFloat cost; +@property (nonatomic) CGSize size; +@property (nonatomic) CGRect rect; +@property (nonatomic) CGPoint point; + +@end diff --git a/Spread/Models/Milk.m b/Spread/Models/Milk.m new file mode 100644 index 0000000..dc035ea --- /dev/null +++ b/Spread/Models/Milk.m @@ -0,0 +1,13 @@ +// +// Milk.m +// Spread +// +// Created by Huy Pham on 8/23/15. +// Copyright (c) 2015 Katana. All rights reserved. +// + +#import "Milk.h" + +@implementation Milk + +@end diff --git a/Spread/Tasks/OtherTask.swift b/Spread/Tasks/OtherTask.swift index 8aec3df..b023bb4 100644 --- a/Spread/Tasks/OtherTask.swift +++ b/Spread/Tasks/OtherTask.swift @@ -14,24 +14,20 @@ class OtherTask: SRemoteTask { var nameSpace: String! init(objectId: String, nameSpace: String) { - super.init() self.objectId = objectId self.nameSpace = nameSpace } - override func getRequestParameters() -> [NSObject : AnyObject]! { - + override func getRequestParameters() -> [AnyHashable: Any] { return ["type": "block"] } - override func getRequestUrl() -> String! { - + override func getRequestUrl() -> String { return "www.google.com" } - override func dequeueCondtion(executingTask: SRemoteTask!) -> Bool { - + override func dequeue(_ executingTask: SRemoteTask) -> Bool { let task = executingTask as! OtherTask if self.objectId != task.objectId { return true @@ -39,8 +35,7 @@ class OtherTask: SRemoteTask { return false } - override func enqueueCondtion(penddingTask: SRemoteTask!) -> Bool { - + override func enqueue(_ penddingTask: SRemoteTask) -> Bool { let task = penddingTask as! OtherTask if self.objectId == task.objectId && self.nameSpace == task.nameSpace { diff --git a/Spread/Tasks/Task.swift b/Spread/Tasks/Task.swift index ac6a2ba..0e4bd31 100644 --- a/Spread/Tasks/Task.swift +++ b/Spread/Tasks/Task.swift @@ -12,26 +12,22 @@ class Task: SRemoteTask { var objectId: String! var nameSpace: String! - - init(objectId: String, nameSpace: String) { + init(objectId: String, nameSpace: String) { super.init() self.objectId = objectId self.nameSpace = nameSpace } - override func getRequestParameters() -> [NSObject : AnyObject]! { - + override func getRequestParameters() -> [AnyHashable: Any] { return ["type": "block"] } - override func getRequestUrl() -> String! { - + override func getRequestUrl() -> String { return "www.google.com" } - override func dequeueCondtion(executingTask: SRemoteTask!) -> Bool { - + override func dequeue(_ executingTask: SRemoteTask) -> Bool { let task = executingTask as! Task if self.objectId != task.objectId { return true @@ -39,8 +35,7 @@ class Task: SRemoteTask { return false } - override func enqueueCondtion(penddingTask: SRemoteTask!) -> Bool { - + override func enqueue(_ penddingTask: SRemoteTask) -> Bool { let task = penddingTask as! Task if self.objectId == task.objectId && self.nameSpace == task.nameSpace { diff --git a/Spread/Utils/Networking.swift b/Spread/Utils/Networking.swift index 1513be6..6571364 100644 --- a/Spread/Utils/Networking.swift +++ b/Spread/Utils/Networking.swift @@ -10,14 +10,14 @@ import UIKit class Networking { - class func getData(handler: ((response: NSDictionary) -> Void)) { + class func getData(_ handler: @escaping ((_ response: NSDictionary) -> Void)) { - let url = NSURL(string: "http://latte.lozi.vn/albums/5437779d72cc6b292f8fc9dd/blocks") - let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in - let response = NSJSONSerialization.JSONObjectWithData(data, - options: NSJSONReadingOptions.MutableLeaves, error: nil) as! NSDictionary - handler(response: response) - } + let url = URL(string: "http://latte.lozi.vn/albums/5437779d72cc6b292f8fc9dd/blocks") + let task = URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in + let response = (try! JSONSerialization.jsonObject(with: data!, + options: JSONSerialization.ReadingOptions.mutableLeaves)) as! NSDictionary + handler(response) + }) task.resume() } } diff --git a/Spread/ViewController.swift b/Spread/ViewController.swift index d4c5d9f..9816dea 100644 --- a/Spread/ViewController.swift +++ b/Spread/ViewController.swift @@ -9,195 +9,191 @@ import UIKit class ViewController: UIViewController { - - // Pool Identifiers. - private let pool1Indentifier = "Pool1Indentifier" - private let pool2Indentifier = "Pool2Indentifier" - private let pool3Indentifier = "Pool3Indentifier" - - private let action1Identifier = "ChangeCarrotName" - - // View components. - private let textField = UITextField() - - private let carrot1Label = UILabel() - private let carrot2Label = UILabel() - private let carrot3Label = UILabel() - private let milkCarrot = Carrot() - - override func loadView() { - super.loadView() - self.view.backgroundColor = UIColor.whiteColor() + // Pool Identifiers. + fileprivate let pool1Indentifier = "Pool1Indentifier" + fileprivate let pool2Indentifier = "Pool2Indentifier" + fileprivate let pool3Indentifier = "Pool3Indentifier" - // Setup view. - self.initView() + fileprivate let action1Identifier = "ChangeCarrotName" - // Setup data. - self.initData() - } - - func initData() { + // View components. + fileprivate let textField = UITextField() - NSLog("Magic is here...") + fileprivate let carrot1Label = UILabel() + fileprivate let carrot2Label = UILabel() + fileprivate let carrot3Label = UILabel() + fileprivate let milkCarrot = Carrot() - let task1 = Task(objectId: "1", nameSpace: "Carrot 1") - - // This one will be cancel. - let task2 = Task(objectId: "1", nameSpace: "Carrot 2") - - let task3 = Task(objectId: "1", nameSpace: "Carrot 2") - - let task4 = Task(objectId: "1", nameSpace: "Carrot 4") - let task5 = Task(objectId: "1", nameSpace: "Carrot 5") - let task6 = Task(objectId: "1", nameSpace: "Carrot 6") - - task1.addHanlder { (response, error) -> Void in - NSLog("Task 1 complete") - } - task2.addHanlder { (response, error) -> Void in - NSLog("Task 2 complete") - } - task3.addHanlder { (response, error) -> Void in - NSLog("Task 3 complete") - } - task4.addHanlder { (response, error) -> Void in - NSLog("Task 4 complete") - } - task5.addHanlder { (response, error) -> Void in - NSLog("Task 5 complete") - } - task6.addHanlder { (response, error) -> Void in - NSLog("Task 6 complete") - } - - let otherTask1 = OtherTask(objectId: "1", nameSpace: "Carrot 2") - - // This one will be remove. - let otherTask2 = OtherTask(objectId: "1", nameSpace: "Carrot 1") - let otherTask3 = OtherTask(objectId: "1", nameSpace: "Carrot 1") - - let otherTask4 = OtherTask(objectId: "1", nameSpace: "Carrot 1") - - otherTask1.addHanlder { (response, error) -> Void in - NSLog("Other task 1 complete") - } - otherTask2.addHanlder { (response, error) -> Void in - NSLog("Other task 2 complete") - } - otherTask3.addHanlder { (response, error) -> Void in - NSLog("Other task 3 complete") - } - otherTask4.addHanlder { (response, error) -> Void in - NSLog("Other task 4 complete") + override func loadView() { + super.loadView() + self.view.backgroundColor = UIColor.white + + // Setup view. + self.initView() + + // Setup data. + self.initData() } - SRemoteTaskManager.addTask(task1) - SRemoteTaskManager.addTask(task2) - SRemoteTaskManager.addTask(otherTask1) - SRemoteTaskManager.addTask(otherTask2) - SRemoteTaskManager.addTask(otherTask3) - SRemoteTaskManager.addTask(otherTask4) - SRemoteTaskManager.addTask(task3) - SRemoteTaskManager.addTask(task4) - SRemoteTaskManager.addTask(task5) - SRemoteTaskManager.addTask(task6) - - // Config Spread pools. - Spread.registerClass(Carrot.classForCoder(), forPoolIdentifier: self.pool1Indentifier) - Spread.registerClass(Carrot.classForCoder(), forPoolIdentifier: self.pool2Indentifier) - Spread.registerClass(Carrot.classForCoder(), forPoolIdentifier: self.pool3Indentifier) - - let pool3 = Spread.getPool(self.pool3Indentifier) - pool3.onEvent(SPoolEvent.OnInitModel, reaction: { (data) -> Void in - - NSLog("Pool reaction on init.") - }) - - pool3.onEvent(SPoolEvent.OnChange, reaction: { (data) -> Void in - - NSLog("Pool reaction change.") - }) - - pool3.onEvent(SPoolEvent.OnRemoveModel, reaction: { (data) -> Void in - - NSLog("Pool reaction on remove.") - }) - - // Register actions for pools. - Spread.registerEvent(self.action1Identifier, - poolIdentifiers: [self.pool1Indentifier, self.pool2Indentifier, self.pool3Indentifier]) - { (data, pool) -> Void in - - // Get new name and id. - let newName = (data as! NSDictionary).valueForKey("name") as! String - let objctId = (data as! NSDictionary).valueForKey("objectId") as! String - - // Select carrots in pool. - let carrots = pool.allObjects().filter({ (item) -> Bool in - let carrot = item as! Carrot - return (carrot.objectId == objctId) + func initData() { + NSLog("Magic is here...") + + let task1 = Task(objectId: "1", nameSpace: "Carrot 1") + + // This one will be cancel. + let task2 = Task(objectId: "1", nameSpace: "Carrot 2") + + let task3 = Task(objectId: "1", nameSpace: "Carrot 2") + let task4 = Task(objectId: "1", nameSpace: "Carrot 4") + let task5 = Task(objectId: "1", nameSpace: "Carrot 5") + let task6 = Task(objectId: "1", nameSpace: "Carrot 6") + + task1.addHanlder { (response, error) -> Void in + NSLog("Task 1 complete") + } + task2.addHanlder { (response, error) -> Void in + NSLog("Task 2 complete") + } + task3.addHanlder { (response, error) -> Void in + NSLog("Task 3 complete") + } + task4.addHanlder { (response, error) -> Void in + NSLog("Task 4 complete") + } + task5.addHanlder { (response, error) -> Void in + NSLog("Task 5 complete") + sleep(5) + } + task6.addHanlder { (response, error) -> Void in + NSLog("Task 6 complete") + } + + let otherTask1 = OtherTask(objectId: "1", nameSpace: "Carrot 2") + + // This tasks will not be enqueued (because of spam) + let otherTask2 = OtherTask(objectId: "1", nameSpace: "Carrot 1") + let otherTask3 = OtherTask(objectId: "1", nameSpace: "Carrot 1") + + let otherTask4 = OtherTask(objectId: "1", nameSpace: "Carrot 1") + + otherTask1.addHanlder { (response, error) -> Void in + NSLog("Other task 1 complete") + } + otherTask2.addHanlder { (response, error) -> Void in + NSLog("Other task 2 complete") + } + otherTask3.addHanlder { (response, error) -> Void in + NSLog("Other task 3 complete") + } + otherTask4.addHanlder { (response, error) -> Void in + NSLog("Other task 4 complete") + } + + SRemoteTaskManager.add(task1) + SRemoteTaskManager.add(task2) + SRemoteTaskManager.add(otherTask1) + SRemoteTaskManager.add(otherTask2) + SRemoteTaskManager.add(otherTask3) + SRemoteTaskManager.add(otherTask4) + SRemoteTaskManager.add(task3) + SRemoteTaskManager.add(task4) + SRemoteTaskManager.add(task5) + SRemoteTaskManager.add(task6) + + // Config Spread pools. + Spread.registerClass(Carrot.classForCoder(), forPoolIdentifier: self.pool1Indentifier, keep: true) + Spread.registerClass(Carrot.classForCoder(), forPoolIdentifier: self.pool2Indentifier) + let pool3 = Spread.registerClass(Carrot.classForCoder(), forPoolIdentifier: self.pool3Indentifier) + + pool3.onEvent(SPoolEvent.onChange, reaction: { (data) -> Void in + NSLog("Pool reaction on init.") + }) + pool3.onEvent(SPoolEvent.onChange, reaction: { (data) -> Void in + NSLog("Pool reaction change.") + }) + pool3.onEvent(SPoolEvent.onRemoveModel, reaction: { (data) -> Void in + NSLog("Pool reaction on remove.") }) - // Change carrots name. - for item in carrots { - let carrot = item as! Carrot - carrot.name = newName + // Register actions for pools. + Spread.registerEvent(self.action1Identifier, + poolIdentifiers: [self.pool1Indentifier, self.pool2Indentifier, self.pool3Indentifier]) + { (data, pool) -> Void in + + // Get new name and id. + let newName = (data as! NSDictionary).value(forKey: "name") as! String + let objctId = (data as! NSDictionary).value(forKey: "objectId") as! String + + // Select carrots in pool. + let carrots = pool.allModels().filter({ (item) -> Bool in + let carrot = item as! Carrot + return (carrot.objectId == objctId as NSString) + }) + + // Change carrots name. + for item in carrots { + let carrot = item as! Carrot + carrot.name = newName as NSString! + } } + + // Create dummies data. + let carrotData = ["name": "One", "objectId": "one"] + + + let milk = Milk() + print(milk.toDictionary()) + + let carrot = Carrot() + print(carrot.toDictionary()) + + // Add object to pool and setup reaction. + let carrotInPool1 = Spread.addObject(carrotData, toPool: self.pool1Indentifier) as! Carrot + carrotInPool1.property("name", on: .onChange) { [weak self] (oldValue, newValue) -> Void in + self?.carrot1Label.text = newValue as? String + } + + let carrotInPool2 = Spread.addObject(carrotData, toPool: self.pool2Indentifier) as! Carrot + carrotInPool2.property("name", on: .onChange) { [weak self] (oldValue, newValue) -> Void in + self?.carrot2Label.text = newValue as? String + } + + let carrotInPool3 = Spread.addObject(carrotData, toPool: self.pool3Indentifier) as! Carrot + carrotInPool3.property("name", target: self, selector: #selector(ViewController.textChange), on: .onChange) } - // Create dummies data. - let carrotData = ["name": "One", "objectId": "one"] - - // Add object to pool and setup reaction. - let carrotInPool1 = Spread.addObject(carrotData, toPool: self.pool1Indentifier) - carrotInPool1.property("name", onEvent: SModelEvent.OnChange) { (oldValue, newValue) -> Void in - self.carrot1Label.text = newValue as? String + func textChange() { + DispatchQueue.main.async { + self.carrot3Label.text = self.textField.text + } } - let carrotInPool2 = Spread.addObject(carrotData, toPool: self.pool2Indentifier) - carrotInPool2.property("name", onEvent: SModelEvent.OnChange) { (oldValue, newValue) -> Void in - self.carrot2Label.text = newValue as? String + func initView() { + self.textField.frame = CGRect(x: 10, y: 40, width: 300, height: 40) + self.textField.addTarget(self, action: #selector(UITextViewDelegate.textViewDidChange(_:)), + for: UIControlEvents.editingChanged) + self.textField.backgroundColor = UIColor.green + + self.carrot1Label.frame = CGRect(x: 10, y: 100, width: 300, height: 40) + self.carrot1Label.backgroundColor = UIColor.yellow + + self.carrot2Label.frame = CGRect(x: 10, y: 160, width: 300, height: 40) + self.carrot2Label.backgroundColor = UIColor.yellow + + self.carrot3Label.frame = CGRect(x: 10, y: 220, width: 300, height: 40) + self.carrot3Label.backgroundColor = UIColor.yellow + + self.view.addSubview(self.textField) + self.view.addSubview(self.carrot1Label) + self.view.addSubview(self.carrot2Label) + self.view.addSubview(self.carrot3Label) } - let carrotInPool3 = Spread.addObject(carrotData, toPool: self.pool3Indentifier) - - NSLog("\(carrotInPool3.toDictionary())") - - carrotInPool3.property("name", target: self, selector: "textChange", onEvent: SModelEvent.OnChange) - } - - func textChange() { - self.carrot3Label.text = self.textField.text - } - - func initView() { - - self.textField.frame = CGRectMake(10, 40, 300, 40) - self.textField.addTarget(self, action: "textViewDidChange:", - forControlEvents: UIControlEvents.EditingChanged) - self.textField.backgroundColor = UIColor.greenColor() - - self.carrot1Label.frame = CGRectMake(10, 100, 300, 40) - self.carrot1Label.backgroundColor = UIColor.yellowColor() - - self.carrot2Label.frame = CGRectMake(10, 160, 300, 40) - self.carrot2Label.backgroundColor = UIColor.yellowColor() - - self.carrot3Label.frame = CGRectMake(10, 220, 300, 40) - self.carrot3Label.backgroundColor = UIColor.yellowColor() - - self.view.addSubview(self.textField) - self.view.addSubview(self.carrot1Label) - self.view.addSubview(self.carrot2Label) - self.view.addSubview(self.carrot3Label) - } - - func textViewDidChange(textField: UITextField) { - - let text = textField.text - Spread.outEvent(self.action1Identifier, - value: ["name": text, "objectId": "one"]) - } + func textViewDidChange(_ textField: UITextField) { + let text = textField.text + Spread.outEvent(self.action1Identifier, + value: ["name": text!, "objectId": "one"]) + } } diff --git a/SpreadTests/Info.plist b/SpreadTests/Info.plist index bba26a6..ba72822 100644 --- a/SpreadTests/Info.plist +++ b/SpreadTests/Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier - katana.$(PRODUCT_NAME:rfc1034identifier) + $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName diff --git a/SpreadTests/SpreadTests.swift b/SpreadTests/SpreadTests.swift index fd4a5d1..a5596f7 100644 --- a/SpreadTests/SpreadTests.swift +++ b/SpreadTests/SpreadTests.swift @@ -10,34 +10,32 @@ import Foundation import Spread import XCTest -class Model: SModel { +class Model: Mapper { dynamic var objectId: String! dynamic var name: String! } class SpreadTests: XCTestCase { + fileprivate let pool1Identifier = "pool1Identifier" + fileprivate let pool2Identifier = "pool2Identifier" + fileprivate let pool3Identifier = "pool3Identifier" + fileprivate let pool4Identifier = "pool4Identifier" - private let pool1Identifier = "pool1Identifier" - private let pool2Identifier = "pool2Identifier" - private let pool3Identifier = "pool3Identifier" - private let pool4Identifier = "pool4Identifier" - - private var model1Name = "" - private var model2Name = "" - private var model3Name = "" + fileprivate var model1Name = "" + fileprivate var model2Name = "" + fileprivate var model3Name = "" // Init data. - private let model1Data = ["name": "One", "objectId": "match all object id"] - private let model2Data = ["name": "Two", "objectId": "match all object id"] - private let model3Data = ["name": "Three", "objectId": "match all object id"] - private let model4Data = ["name": "Four", "objectId": "match all object id"] - private let model5Data = ["name": "Five", "objectId": "match all object id"] + fileprivate let model1Data = ["name": "One", "objectId": "match all object id"] + fileprivate let model2Data = ["name": "Two", "objectId": "match all object id"] + fileprivate let model3Data = ["name": "Three", "objectId": "match all object id"] + fileprivate let model4Data = ["name": "Four", "objectId": "match all object id"] + fileprivate let model5Data = ["name": "Five", "objectId": "match all object id"] - private let poolChangeNameEvent = "ChangeName" + fileprivate let poolChangeNameEvent = "ChangeName" override func setUp() { - super.setUp() // Register class. @@ -53,9 +51,9 @@ class SpreadTests: XCTestCase { self.pool3Identifier, self.pool4Identifier]) { (value, spool) -> Void in - let objectId = (value as! NSDictionary).valueForKey("objectId") as! String - let newName = (value as! NSDictionary).valueForKey("name") as! String - let models = spool.allObjects().filter({ (model) -> Bool in + let objectId = (value as! NSDictionary).value(forKey: "objectId") as! String + let newName = (value as! NSDictionary).value(forKey: "name") as! String + let models = spool.allModels().filter({ (model) -> Bool in return (model as! Model).objectId == objectId }) for item in models { @@ -66,38 +64,36 @@ class SpreadTests: XCTestCase { // Add data to pool and binding data. let model1 = Spread.addObject(model1Data, toPool: self.pool1Identifier) - model1.property("name", onEvent: SModelEvent.OnChange) { (oldValue, newValue) -> Void in + model1.property("name", on: .onChange) { (oldValue, newValue) -> Void in self.model1Name = newValue as! String } Spread.addObject(model5Data, toPool: self.pool1Identifier) let model2 = Spread.addObject(model2Data, toPool: self.pool2Identifier) - model2.property("name", onEvent: SModelEvent.OnChange) { (oldValue, newValue) -> Void in + model2.property("name", on: .onChange) { (oldValue, newValue) -> Void in self.model2Name = newValue as! String } let model3 = Spread.addObject(model3Data, toPool: self.pool3Identifier) - model3.property("name", onEvent: SModelEvent.OnChange) { (oldValue, newValue) -> Void in + model3.property("name", on: .onChange) { (oldValue, newValue) -> Void in self.model3Name = newValue as! String } } override func tearDown() { - super.tearDown() } func testCountingAddAndRemoveObejct() { - let pool4 = Spread.getPool(self.pool4Identifier) - let numberObjectBeforeAdd = pool4.allObjects().count + let numberObjectBeforeAdd = pool4?.allModels().count let model = Spread.addObject(model4Data, toPool: self.pool4Identifier) - let numberObjectAfterAdded = pool4.allObjects().count - XCTAssertEqual(numberObjectBeforeAdd, numberObjectAfterAdded - 1) + let numberObjectAfterAdded = pool4?.allModels().count + XCTAssertEqual(numberObjectBeforeAdd, numberObjectAfterAdded! - 1) - Spread.removeObject(model, fromPool: self.pool4Identifier) - let numberObjectAfterRemove = pool4.allObjects().count - XCTAssertEqual(numberObjectAfterAdded, numberObjectAfterRemove + 1) + Spread.removeModel(model, fromPool: self.pool4Identifier) + let numberObjectAfterRemove = pool4?.allModels().count + XCTAssertEqual(numberObjectAfterAdded, numberObjectAfterRemove! + 1) } func testReactionWhenMatchObjectId() { @@ -115,7 +111,6 @@ class SpreadTests: XCTestCase { } func testReactionNotMatchObjectId() { - Spread.outEvent(self.poolChangeNameEvent, value: ["name": "A new name", "objectId": "match all object id"]) @@ -129,7 +124,6 @@ class SpreadTests: XCTestCase { } func testRemoveReact() { - Spread.outEvent(self.poolChangeNameEvent, value: ["name": "Name before remove", "objectId": "match all object id"]) @@ -143,12 +137,11 @@ class SpreadTests: XCTestCase { } func testPerformance() { - - self.measureBlock() { - for i in 1...1000 { + self.measure() { + for _ in 1...1000 { Spread.addObject(self.model4Data, toPool: self.pool4Identifier) } - for i in 1...2 { + for _ in 1...2 { Spread.outEvent(self.poolChangeNameEvent, value: ["name": "A new name", "objectId": "match all object id"]) } @@ -156,8 +149,7 @@ class SpreadTests: XCTestCase { } func testRemovePool() { - - Spread.removePoolWithIdentifier(self.pool2Identifier) + Spread.removePool(withIdentifier: self.pool2Identifier) let pool: SPool? = Spread.getPool(self.pool2Identifier) XCTAssertNil(pool, "Must be nil") }