6

我有一个excel文件。

我已经将该文件转换为 .csv 格式并将该文件导入到基础并将其转换为 .sqlite 文件。

所以问题是:

有什么方法可以将其导入 ios 应用程序并操作数据。

有没有办法像核心数据一样使用它或将该文件导入核心数据。

请参考任何好的教程,最好是视频教程或其他一些好的教程。

4

3 回答 3

4

您可以直接将其与 FMDB 库一起使用:https ://github.com/ccgus/fmdb 另一种选择是将该文件导入核心数据,但这有点棘手。如果您按照以下步骤操作,您可以这样做:

  1. 在您的应用程序中创建空的 SQLite 数据库并在模拟器中运行您的应用程序。
  2. 在您的计算机上打开模拟器目录并找到 SQLite 数据库文件。
  3. 使用 SQLite 命令行工具或类似“SQLite 数据浏览器”GUI 工具 ( http://sqlitebrowser.sourceforge.net/ ) 来查看它。
  4. 将您的数据导入此数据库文件,而无需更改核心数据元表中的结构和数据。
  5. 最后,您已经准备好与核心数据一起使用的 SQLite 数据库文件。因此,您将其放入您的应用程序包中。
  6. 在第一次启动应用程序时,您应该在配置核心数据堆栈之前将您的 SQLite 数据库文件复制到适当的目录(您知道应该将文件放在哪里 - 您已经在模拟器应用程序目录中找到了它)。

这听起来有点复杂,但它的工作原理;)

关于运送核心数据的预填充数据的好文章:http ://www.objc.io/issue-4/importing-large-data-sets-into-core-data.html

于 2013-10-22T21:12:10.710 回答
3

更新

请注意更新后的回复。

有什么方法可以将它(SQLite)导入 ios 应用程序并操作数据?

您可以将 sqlite 文件导入 Xcode,只需使用 Add New File 将其添加为资源...但是您将其与 Core Data 一起使用的能力有限(除非它是使用 Core Data 创建的)。您可以查看前面引用的objc.io 文章,该文章介绍了如何处理 Xcode 项目中的预填充数据。这是该文章的相关部分。

NSFileManager* fileManager = [NSFileManager defaultManager];
NSError *error;

if([fileManager fileExistsAtPath:self.storeURL.path]) {
    NSURL *storeDirectory = [self.storeURL URLByDeletingLastPathComponent];
    NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:storeDirectory
                                          includingPropertiesForKeys:nil
                                                             options:0
                                                        errorHandler:NULL];
    NSString *storeName = [self.storeURL.lastPathComponent stringByDeletingPathExtension];
    for (NSURL *url in enumerator) {
        if (![url.lastPathComponent hasPrefix:storeName]) continue;
        [fileManager removeItemAtURL:url error:&error];
    }
    // handle error
}

NSString* bundleDbPath = [[NSBundle mainBundle] pathForResource:@"seed" ofType:@"sqlite"];
[fileManager copyItemAtPath:bundleDbPath toPath:self.storeURL.path error:&error];

NSDictionary *infoDictionary = [NSBundle mainBundle].infoDictionary;
NSString* bundleVersion = [infoDictionary objectForKey:(NSString *)kCFBundleVersionKey];
NSString *seedVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"SeedVersion"];
if (![seedVersion isEqualToString:bundleVersion]) {
    // Copy the seed database
}

// ... after the import succeeded
[[NSUserDefaults standardUserDefaults] setObject:bundleVersion forKey:@"SeedVersion"];

假设想要导入 CSV 文件而不是 Excel 或 SQLite...由于这是一个常见问题,这里有一个简单的解析器,可以用来将 CSV 数据合并到 Xcode 项目中。

func parseCSV (contentsOfURL: NSURL, encoding: NSStringEncoding, error: NSErrorPointer) -> [(name:String, detail:String, price: String)]? {
    // Load the CSV file and parse it
    let delimiter = ","
    var items:[(name:String, detail:String, price: String)]?

    if let content = String(contentsOfURL: contentsOfURL, encoding: encoding, error: error) {
        items = []
        let lines:[String] = content.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as [String]

        for line in lines {
            var values:[String] = []
            if line != "" {
                // For a line with double quotes
                // we use NSScanner to perform the parsing
                if line.rangeOfString("\"") != nil {
                    var textToScan:String = line
                    var value:NSString?
                    var textScanner:NSScanner = NSScanner(string: textToScan)
                    while textScanner.string != "" {

                        if (textScanner.string as NSString).substringToIndex(1) == "\"" {
                            textScanner.scanLocation += 1
                            textScanner.scanUpToString("\"", intoString: &value)
                            textScanner.scanLocation += 1
                        } else {
                            textScanner.scanUpToString(delimiter, intoString: &value)
                        }

                        // Store the value into the values array
                        values.append(value as! String)

             // Retrieve the unscanned remainder of the string
                        if textScanner.scanLocation < count(textScanner.string) {
                            textToScan = (textScanner.string as NSString).substringFromIndex(textScanner.scanLocation + 1)
                        } else {
                            textToScan = ""
                        }
                        textScanner = NSScanner(string: textToScan)
                    }

                // For a line without double quotes, we can simply separate the string
                // by using the delimiter (e.g. comma)
                } else  {
                    values = line.componentsSeparatedByString(delimiter)
                }

                // Put the values into the tuple and add it to the items array
                let item = (name: values[0], detail: values[1], price: values[2])
                items?.append(item)
            }
        }
    }

    return items
}

来源文章

另一种选择是使用最初在 Ray W.工具列表中提到的核心数据编辑器工具。这个GUI 编辑器试图使处理 CSV 数据导入更容易。

有没有办法像核心数据一样使用它或将该文件导入核心数据?

所以 SQLite 数据库与 Core Data 不同(它是一个对象图持久性......)。我正要在这里进行诽谤,但苹果的核心数据常见问题解答说得比我好......:

如何将现有的 SQLite 数据库与 Core Data 一起使用?

你没有。尽管 Core Data 支持 SQLite 作为其持久存储类型之一,但数据库格式是私有的。您不能使用原生 SQLite API 创建 SQLite 数据库并将其直接与 Core Data 一起使用(也不应该使用原生 SQLite API 操作现有的 Core Data SQLite 存储)。如果您有现有的 SQLite 数据库,则需要将其导入核心数据存储(请参阅高效导入数据)。

所以这是官方的回答。提供的任何其他东西都只是一种解决不应该这样做的事实的方法。

但是,鉴于您还有一个 CSV 文件,您还有其他一些选择。过去,我构建了一个文件阅读器来使用流阅读器检查 CSV 文件的内容。这是要点,但是我的文件可能有一些其他格式,所以这可能需要调整。您还可以查看使用任何读取文件内容的对象。例如; 想到一个更简单的技术:

  1. 在NSString类上使用 initWithContentsOfFile
  2. 在内存中为您提供一个带有 CSV 的字符串
  3. 迭代每一行的字符串
  4. 使用逗号遍历该行并对每条数据执行一些操作

NSString *fileContents = [NSString stringWithContentsOfFile:@"myfile.txt"]; NSArray *lines = [fileContents componentsSeparatedByString:@"\n"]; //循环并将行数组中的每一行拆分为有用的数据

NSString

假设您真的想在 iOS 中使用 SQLite,尽管有警告...您可以将 sqlite3 库添加到您的项目中。有关如何使用 SQLite 而不是 Core Data 的完整详细信息。AppCoda提供了众多在线教程之一

涵盖了基础知识(示例项目):

保存...

- (IBAction)saveInfo:(id)sender {
    // Prepare the query string.    
    NSString *query = [NSString stringWithFormat:@"insert into peopleInfo values(null, '%@', '%@', %d)", self.txtFirstname.text, self.txtLastname.text, [self.txtAge.text intValue]];

    // Execute the query.
    [self.dbManager executeQuery:query];

    // If the query was successfully executed then pop the view controller.
    if (self.dbManager.affectedRows != 0) {
        NSLog(@"Query was executed successfully. Affected rows = %d", self.dbManager.affectedRows);

        // Pop the view controller.
        [self.navigationController popViewControllerAnimated:YES];
    }
    else{
        NSLog(@"Could not execute the query.");
    }
}

正在编辑...

-(void)loadInfoToEdit{
    // Create the query.
    NSString *query = [NSString stringWithFormat:@"select * from peopleInfo where peopleInfoID=%d", self.recordIDToEdit];

    // Load the relevant data.
    NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];

    // Set the loaded data to the textfields.
    self.txtFirstname.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"firstname"]];
    self.txtLastname.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"lastname"]];
    self.txtAge.text = [[results objectAtIndex:0] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:@"age"]];
}

正在删除...

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the selected record.
        // Find the record ID.
        int recordIDToDelete = [[[self.arrPeopleInfo objectAtIndex:indexPath.row] objectAtIndex:0] intValue];

        // Prepare the query.
        NSString *query = [NSString stringWithFormat:@"delete from peopleInfo where peopleInfoID=%d", recordIDToDelete];

        // Execute the query.
        [self.dbManager executeQuery:query];

        // Reload the table view.
        [self loadData];
    }
}

回复:请参考任何好的教程,最好是视频教程或其他一些好的教程

以下教程应该满足您的需求。有很多关于这个主题的教程,你可以查看 www.lynda.com,详细了解如何使用 SQLite 构建 iOS 应用程序(完全访问需要一些费用,但是搜索 Youtube,因为他们发布了涵盖这些主题的示例电影时间)。

http://www.youtube.com/watch?v=bC3F8a4F_KE(见视频中的 1:17)

于 2013-10-22T19:40:47.127 回答
0

如果您有一个 .sql 文件,您只需转到文件 - 添加文件将其导入您的项目。另外,请记住,如果您将 .sql 文件留在包中,它将是只读的。因此,除非您希望它是只读的,否则您应该创建新组并将 .sql 放在那里。

于 2013-10-23T09:29:49.820 回答