【发布时间】:2015-07-02 21:35:07
【问题描述】:
今天我阅读并创建了大约 10 个与 Core Data 相关的项目。我终于完成了我需要的,但我不确定这种方法是否很好
我想根据用户设备语言更改书名,我会用
let locale = NSLocale.preferredLanguages()[0] as! String
但首先要测试 Core Data 的实现
核心数据设置
源代码
// Get the data from Core Data and change the book title base on the lang
func printBooks(){
let request = NSFetchRequest(entityName: "Langs")
let predicate: NSPredicate = NSPredicate(format: "lang==%@", "fr");
request.returnsObjectsAsFaults = false;
request.predicate = predicate;
let result:NSArray = context.executeFetchRequest(request, error: nil)!;
var frTitle: String!
if(result.count > 0){
for res in result {
let resTmp = res as! NSManagedObject
frTitle = resTmp.valueForKey("langTitle") as! String
}
} else {
println("empty");
}
let requestTwo = NSFetchRequest(entityName: "Book")
requestTwo.returnsObjectsAsFaults = false;
let resultTwo:NSArray = context.executeFetchRequest(requestTwo, error: nil)!;
if(resultTwo.count > 0){
for res in resultTwo {
let resTmpTwo = res as! NSManagedObject
// rename the title
resTmpTwo.setValue(frTitle, forKey: "title");
}
// add to NSArray
entriesArray = resultTwo;
} else {
println("empty two");
}
}
// Adds the new book with the fr version
func insertBook(){
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context: NSManagedObjectContext = appDel.managedObjectContext!
let newBook = NSEntityDescription.insertNewObjectForEntityForName("Book", inManagedObjectContext: context) as! DB.Book
newBook.setValue("Sir Arthur Conan Doyle", forKey: "author")
newBook.setValue("Sherlock Holmes", forKey: "title")
let newLang = NSEntityDescription.insertNewObjectForEntityForName("Langs", inManagedObjectContext: context) as! DB.Langs
newLang.setValue("fr", forKey: "lang")
newLang.setValue("Sherlock Holmes fr - test", forKey: "langTitle")
newBook.setValue(newLang, forKey: "lanBook")
context.save(nil)
println("Saved");
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.entriesArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell_one", forIndexPath: indexPath) as! UITableViewCell
let db = entriesArray[indexPath.row] as! NSManagedObject
// result in the UITableView is: Sherlock Holmes fr - test
cell.textLabel?.text = db.valueForKey("title") as? String
return cell
}
代码确实改变了书名,但可以做得更好。我不确定如何处理大量书籍。
任何知道必须如何完成的人,请花点时间并用一些代码回答:)
还请原谅我的英语不好..
【问题讨论】:
标签: swift core-data localization relationship