-
-
Save NghiaTranUIT/797fd0bd26b1ae219bea to your computer and use it in GitHub Desktop.
BaseModel Model -> SQLite statement using property inspection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Mantle.h> | |
@interface BaseModel : MTLModel <MTLJSONSerializing> | |
@property (nonatomic) int64_t id; | |
@property (nonatomic) NSTimeInterval createdUtc; | |
@property (nonatomic) NSTimeInterval modifiedUtc; | |
- (NSString *)createTableStatement; | |
- (NSString *)className; | |
- (NSString *)updateStatement; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <ObjectiveSugar.h> | |
#import <FTGPropertyMaestro.h> | |
@interface BaseModel () | |
@end | |
@implementation BaseModel | |
+ (NSDictionary *)JSONKeyPathsByPropertyKey { | |
return @{@"id": @"id", | |
@"createdUtc": @"createdUtc", | |
@"modifiedUtc": @"modifiedUtc", | |
}; | |
} | |
- (NSString *)className { | |
return NSStringFromClass([self class]); | |
} | |
- (NSString *)createTableStatement { | |
NSMutableString *statement = [NSMutableString string]; | |
[statement appendFormat:@"CREATE TABLE %@ (", [self className]]; | |
[self.properties each:^(FTGProperty *property) { | |
NSString *name = property.name; | |
NSString *dataType = [self dataTypeFromProperty:property]; | |
NSString *primaryKey = [name isEqualToString:@"id"] ? @" PRIMARY KEY NOT NULL" : @""; | |
[statement appendFormat:@"%@ %@ %@,", name, dataType, primaryKey]; | |
}]; | |
[statement appendString:@");"]; | |
return statement; | |
} | |
- (NSString *)updateStatement { | |
return @""; | |
} | |
#pragma mark - Properties | |
- (NSArray *)properties { | |
NSMutableArray *properties = [NSMutableArray array]; | |
// XPBaseModel is the superclass, it has id, createdUtc, modifiedUtc | |
[properties addObjectsFromArray:[FTGPropertyMaestro propertiesForClass:[self superclass]]]; | |
[properties addObjectsFromArray:[FTGPropertyMaestro propertiesForClass:[self class]]]; | |
// Only interested in our declared properties | |
NSArray *keys = [[self class] JSONKeyPathsByPropertyKey].allKeys; | |
return [properties select:^BOOL(FTGProperty *property) { | |
return [keys containsObject:property.name]; | |
}]; | |
} | |
- (NSString *)dataTypeFromProperty:(FTGProperty *)property { | |
NSDictionary *mapping = @{@"q": @"INT", | |
@"d": @"REAL", | |
@"NSString": @"TEXT", | |
}; | |
return mapping[property.name]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment