我在swift中編寫了應用程序,它有一個視圖控制器,我更改了其中的一些設置,例如:所有視圖控制器標籤和標題都會更改。 但我的問題是,當我更改應用程序設置,我將它們存儲在覈心數據中,並且當我從核心數據獲取時,我使用導航欄按鈕返回到父視圖控制器,我什麼也得不到相同的數據!但設置視圖控制器,當我再次去它加載正確的數據! 如果我關閉了應用程序並重新打開它,該應用程序將加載正確的數據! 所以我的問題是如何重新加載或重新啓動編程的第一個視圖控制器或整個應用程序?如何在swift中刷新或重新加載應用程序數據2
爲了更好的理解我的問題,下面是我的父視圖控制器裏面包含的導航欄。
代碼:
import UIKit
import AVKit
import AVFoundation
import CoreData
class playVideo: UIViewController {
//data source
var languageDB = [NSManagedObject]()
let managedContext = AppDelegate().managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.hidesBackButton = true
change_language()
}
override func viewDidLayoutSubviews() {
self.view.setNeedsDisplay()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
change_language()
}
func change_language(){
Insert("فارسی")//insert default language
fetch("Language")
let Language = languageDB[0]
let row_value : String = Language.valueForKey("lang") as! String
if(row_value == "فارسی"){
self.navigationItem.title = "پخش زنده تصاویر از حرم مطهر رضوی"
self.navigationItem.backBarButtonItem?.title = "صفحه اصلی"
}else if(row_value == "English"){
self.navigationItem.title = "Live broadcast from razavi holy shrine"
self.navigationItem.backBarButtonItem?.title = "Main Page"
}else if(row_value == "العربية"){
self.navigationItem.title = "لايف صور من مقام رضوي"
self.navigationItem.backBarButtonItem?.title = "صفحةابتدائي"
}
}
//Insert Function
func Insert(lang : String) {
let check_empty = entityIsEmpty("Language")
if(check_empty != true){
let saveLanguage = NSEntityDescription.insertNewObjectForEntityForName("Language", inManagedObjectContext: managedContext)
// add our data
saveLanguage.setValue(lang, forKey: "lang")
//2
do {
try managedContext.save()
//3
languageDB.append(saveLanguage)
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}//end of check empty if
}
//fetch Functions
func fetch(entity: String){
let langfetch = NSFetchRequest(entityName: entity)
do{
let results = try managedContext.executeFetchRequest(langfetch)
languageDB = results as! [NSManagedObject]
}catch{
fatalError("bad things happend \(error)")
}
}
//check entity is empty Function
func entityIsEmpty(entity: String) -> Bool
{
let request = NSFetchRequest(entityName: entity)
do{
let results = try managedContext.executeFetchRequest(request)
languageDB = results as! [NSManagedObject]
}catch{
fatalError("Cant handel entity \(error)")
}
if languageDB.count != 0
{
return true
}
else
{
return false
}
}
func Refresh() {
// Do some reloading of data and update the table view's data source
// Fetch more objects from a web service, for example...
self.dismissViewControllerAnimated(true, completion: nil)
self.navigationController!.dismissViewControllerAnimated(true, completion: nil)
navigationController!.popViewControllerAnimated(true)
self.navigationItem.hidesBackButton = true
change_language()
}
}
不要大寫'Insert'和'Refresh'函數名稱!它使你的代碼非常難讀。 –
@TimVermeulen感謝提示 – anonymox