更新
请注意更新后的回复。
有什么方法可以将它 (SQLite) 导入 ios 应用程序并操作数据?
您可以将 sqlite 文件导入 Xcode,只需使用 Add New File 将其添加为资源...但是您将无法与 Core Data 一起使用它(除非它是使用 Core Data 创建的)。可以查看前面引用的objc.io article,其中介绍了如何处理 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
}
(Source article)
另一种选择是使用最初在 Ray W.list of tools 中提到的核心数据编辑器工具。这个GUI editor 试图使处理 CSV 数据导入更容易。
有没有办法像核心数据一样使用它或将该文件导入核心数据?
所以 SQLite 数据库与 Core Data 不同(它是一个对象图持久性......)。我正要在这里大肆抨击,但 Apple 的 Core Data FAQ 说得比我好......:
如何将现有的 SQLite 数据库与 Core Data 结合使用?
你没有。尽管 Core Data 支持 SQLite 作为其持久性之一
存储类型,数据库格式是私有的。你不能创建一个
SQLite 数据库使用原生 SQLite API 并直接与 Core 一起使用
数据(也不应该操作现有的 Core Data SQLite 存储
使用本机 SQLite API)。如果你有一个现有的 SQLite 数据库,你
需要将其导入核心数据存储(请参阅有效导入
数据)。
所以这是官方的答案。提供的其他任何东西都只是一种解决人们不应该这样做的事实的方法。
但是,鉴于您还有一个 CSV 文件,您还有其他一些选择。过去,我构建了一个文件阅读器来使用流阅读器检查 CSV 文件的内容。这是其中的gist,但是我的文件可能有一些其他格式,所以这可能需要调整。您还可以查看使用任何读取文件内容的对象。例如;想到一个更简单的技术:
- 在 NSString 类上使用 initWithContentsOfFile
- 为您提供内存中包含 CSV 的字符串
- 为每一行迭代字符串
- 使用逗号遍历该行并对每条数据执行一些操作
NSString *fileContents = [NSString stringWithContentsOfFile:@"myfile.txt"];
NSArray *lines = [fileContents componentsSeparatedByString:@"\n"];
//循环并将lines数组中的每一行拆分为有用的数据
假设您真的想在 iOS 中使用 SQLite,尽管有警告...您可以将 sqlite3 库添加到您的项目中。有关如何使用 SQLite 而不是 Core Data 的完整详细信息。众多在线教程之一是AppCoda
涵盖了基础知识 (sample project):
正在保存...
- (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];
}
}
Re: 请参考任何好的教程,最好是视频教程或一些
其他不错的。
以下教程应该可以满足您的需求。有很多关于这个主题的教程,你可以查看 www.lynda.com,详细了解如何使用 SQLite 构建 iOS 应用程序(完全访问需要一些费用,但是搜索 Youtube,因为他们发布了涵盖这些主题的示例电影时间)。
http://www.youtube.com/watch?v=bC3F8a4F_KE(见视频中的 1:17)