Last active
November 25, 2015 12:54
-
-
Save zld/576f0a9e7395e3b3d249 to your computer and use it in GitHub Desktop.
insert multiline datas into sqlite in Objective-C
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
+ (BOOL)insertOrReplaceObjects:(NSArray *)objects { | |
__block BOOL result = NO; | |
NSArray *properties = [self allColumbs]; | |
[self inDatabase:^(FMDatabase *db) { | |
NSMutableString *sql = [NSMutableString stringWithFormat:@"insert or replace into %@ ", [self tableName]]; | |
[sql appendFormat:@"('%@') values ",[properties componentsJoinedByString:@"','"]]; | |
NSMutableArray *objectsValues = [[NSMutableArray alloc] init]; | |
for (__typeof(self) obj in objects) { | |
NSDictionary *valueDict = [obj dictionaryWithValuesForKeys:properties]; | |
NSMutableArray *valueArrayForOneObject = [NSMutableArray arrayWithCapacity:[properties count]]; | |
for (NSString *p in properties) { | |
id obj = [valueDict valueForKey:p]; | |
NSString *valueString = @""; | |
if ([obj isKindOfClass:[NSNull class]] || obj == nil) { | |
valueString = @"null"; | |
} else { | |
valueString = [NSString stringWithFormat:@"'%@'", obj]; | |
} | |
[valueArrayForOneObject addObject:valueString]; | |
} | |
NSString *valuesInString = [NSString stringWithFormat:@"(%@)", [valueArrayForOneObject componentsJoinedByString:@","]]; | |
[objectsValues addObject:valuesInString]; | |
} | |
[sql appendString:[objectsValues componentsJoinedByString:@","]]; | |
[sql appendString:@";"]; | |
result = [db executeUpdate:sql]; | |
if (!result) { | |
NSLog(@"%@", [db lastErrorMessage]); | |
} | |
}]; | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment