【发布时间】:2018-09-04 05:38:55
【问题描述】:
我正在从我的json file 中检索数据,其中包含timings 的sunrise、sunset 和midnight。我想做array for sunrise、array for sunset和array for midnight。并将我的数组保存在 SQLite 中的 sunriseColumn 、 sunsetColumn 和 midnightColumn 中。
但我有点困惑如何以正确的方式做到这一点。
我的 ViewDidLoad() 中有什么
- (void)viewDidLoad {
[super viewDidLoad];
[self saveinDatabase];
NSURL *url = [NSURL fileURLWithPath:@"/Users/macbook/Desktop/Test/Test/myFile.json"];
NSString *fileContent = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(@"Json data is here %@", fileContent);
在字典中保存数据
NSArray *data = [[theFeedString JSONValue] objectForKey:@"data"];
for (NSDictionray *dict in data) {
NSString *timings = [[dict objectForKey:@"timings"] intValue];
NSArray *sunriseArray = [objectForKey:@"sunrise"]
NSArray *sunsetArray = [objectForKey:@"sunset"]
NSArray *midnight = [objectForKey:@"midnight"]
}
在我的控制台中,我从我的 json 中获取所有数据,我的 json 看起来像这样
{
"data": [
{
"timings": {
"Sunrise": "07:14 (PKT)",
"Sunset": "18:15 (PKT)",
"Midnight": "00:45 (PKT)"
}
},
{
"timings": {
"Sunrise": "07:13 (PKT)",
"Sunset": "06:40 (PKT)",
"Midnight": "00:45 (PKT)"
}
}
]
}
一种在SQLite中存储数据的方法
-(void) saveinDatabase {
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, TRUE);
docsDir = dirPaths[0];
_dbPath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"mydatabase.db"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:_dbPath] == NO) {
const char *dbPathagain = [_dbPath UTF8String];
if(sqlite3_open(dbPathagain, &_DB) == SQLITE_OK ) {
char *errorMessage;
const char *sql_statement = "CREATE TABLE IF NOT EXISTS jsontable(ID integer primary key, sunrise text, sunset text, midnight text)";
NSLog(@"created table success");
sqlite3_stmt *statement;
const char *dbPathagain = [ _dbPath UTF8String];
if(sqlite3_open(dbPathagain, &_DB) == SQLITE_OK ) {
NSString *insertSQLData = [NSString stringWithFormat:@"INSERT INTO jsontable(sunrise, sunset, midnight) VALUES (\"%@\", \"%@\", \"%@\")", sunriseArray, sunsetArray, midnightArray];
const char *insert_statement = [insertSQLData UTF8String];
sqlite3_prepare_v2(_DB, insert_statement, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE) {
NSLog(@"data added successfully");
NSLog(@"here is sunrise times %@", sunriseArray);
}
else {
NSLog(@"could not add timings");
}
sqlite3_finalize(statement);
sqlite3_close(_DB);
}
if (sqlite3_exec(_DB, sql_statement, NULL, NULL, &errorMessage) != SQLITE_OK) {
NSLog(@"failed to create table");
}
sqlite3_close(_DB);
}
else {
NSLog(@"failed to open db or cretate table");
}
}
}
}
【问题讨论】:
-
此代码会将所有 3 个数组保存在单行中。你真的想实现这个目标吗?
-
我可以运行循环,以便将三个数组中的一项一项添加到一行中
-
如果要将单个数据存储在单行中,则无需创建单独的数组。只需循环到名为“data”的数组并获取每个字典并将其存储在数据库中
-
你能帮我解答一下吗
-
你能告诉我为什么你应该想要 3 个不同的数组吗?您在哪里遇到问题?
标签: ios objective-c sqlite nsarray nsdictionary