2016-06-30 56 views
0

在coredata中保存字符串以及我保存的所有字符串將在tableview中顯示爲labeltext。字符串來自alertview中的文本字段。它會正確保存字符串,但是我必須再次關閉並運行項目,才能在tableview中顯示新字符串。在添加對象後更新tableview

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

@IBOutlet var tableView: UITableView! 

var buyingList : [BuyList] = [] 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    gettingData() 


    self.tableView.dataSource = self 
    self.tableView.delegate = self 

} 


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.buyingList.count 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    // let Cell = tableView.dequeueReusableCellWithIdentifier("identifier") as UITableViewCell! 
    let Cell = UITableViewCell() 



    let tableViewData = self.buyingList.reverse()[indexPath.row] 
    Cell.textLabel?.text = tableViewData.buyList 

    return Cell 
} 

func refresh(){ 
    dispatch_async(dispatch_get_main_queue()) {() -> Void in 
     dump(self.buyingList) 
     self.tableView.reloadData() 
    } 
} 

@IBAction func addButton(sender: UIBarButtonItem) { 
    nameOfPicture() 
} 

func nameOfPicture() { 
    let alert = UIAlertController(title: "Tilføj", message: "", preferredStyle: UIAlertControllerStyle.Alert) 

    let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) 
    alert.addAction(cancel) 

    alert.addTextFieldWithConfigurationHandler { (textField) -> Void in 

    } 

    alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in 

     let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext 

     let savingData = NSEntityDescription.insertNewObjectForEntityForName("BuyList", inManagedObjectContext: context) as! BuyList 

     let textf = alert.textFields![0] as UITextField 

     savingData.buyList = textf.text 

     do { 
      try context.save() 

     } catch _ { 

     } 

    })) 

    self.presentViewController(alert, animated: true, completion: nil) 
} 

func gettingData() { 
    let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext 

    let request = NSFetchRequest(entityName: "BuyList") 

    var results : [AnyObject]? 

    do { 
     results = try context.executeFetchRequest(request) 
    } catch _ { 
     results = nil 
    } 

    if results != nil { 
     self.buyingList = results! as! [BuyList] 
    } 
} 
} 
+1

打電話給你的'refresh'函數,其中你希望更新你的表格視圖。 – Dershowitz123

+0

這應該在alertview中的自定義「確定」按鈕下,但沒有任何反應 – jonask

+0

當您在警報操作中按「確定」時,您想要重新加載表格視圖? – Dershowitz123

回答

0

您提取數據後,tableview不會重新加載。你獲得的數據功能應該看起來像:

if results != nil { 
    self.buyingList = results! as! [BuyList] 
    self.tableView.reloadData() 
} 

,如果它不顯示在此調用後您的表中的數據,這意味着你的結果ERGO你buyingList是空

相關問題