Skip to content

Instantly share code, notes, and snippets.

@NghiaTranUIT
Forked from onmyway133/BaseModel.h
Created November 16, 2015 12:53
Show Gist options
  • Save NghiaTranUIT/797fd0bd26b1ae219bea to your computer and use it in GitHub Desktop.
Save NghiaTranUIT/797fd0bd26b1ae219bea to your computer and use it in GitHub Desktop.
BaseModel Model -> SQLite statement using property inspection
#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
#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