2016-10-02 5 views
0

У меня есть два tableView, работающих в моем проекте. Я успешно передал данные из моего первого tableView во второй контроллер tableView с помощью segue. Я пытаюсь сохранить данные, которые я передал secondViewController, используя NSUserDefaults. Мой частичный код ниже ....Сохранение массива TableView в indexPath в Swift

Первый VC:

var tableView: UITableView! 
var DataArray = ["Bus","Helicopter","Truck","Boat","Bicycle","Motorcycle","Plane","Train","Car","S cooter","Caravan"] 
var sendSelectedData = NSString() 


override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
let indexPath = tableView.indexPathForSelectedRow! 
let currentCell = tableView.cellForRow(at: indexPath) as UITableViewCell! 
     // print(indexPath) 
     // print(currentCell) 

sendSelectedData = (currentCell!.textLabel?.text)! as String as NSString 
performSegue(withIdentifier: "ShowDetails", sender: indexPath) 

} 

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 

    let selectedIndex = sender as! NSIndexPath 
    let currentCell = tableView.cellForRow(at: selectedIndex as IndexPath)! 
    self.sendSelectedData = (currentCell.textLabel?.text)! as String as NSString 
    if segue.identifier == "ShowDetails" { 

    let viewController = segue.destination as! SecondController 
    viewController.newItem = (self.sendSelectedData as String) 

    } 
} 

Второй VC:

var NewArray = [""] 

var newItem: String = "" 

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

    NewArray.insert(newItem, at: Array.count) 
    self.tableView?.beginUpdates() 

    // NewArray.append(newItem) 

    let defaults = UserDefaults.standard 
    defaults.object(forKey: "NewArray") 

    self.tableView?.endUpdates() 
    } 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell 

    cell.textLabel?.text = NewArray[(indexPath as NSIndexPath).row] as String 
    return cell 
    } 

    func insertRowsAtIndexPaths(indexPaths: [AnyObject], withRowAnimation animation: UITableViewRowAnimation) { 
    } 

    func reloadRowsAtIndexPaths(indexPaths: [AnyObject], withRowAnimation animation: UITableViewRowAnimation) { 

    } 

Я следую https://grokswift.com/uitableview-updates/ статье для достижения этой цели ....

Спасибо заранее.

ответ

1

В AppDelegateapplicationDidFinishLaunching зарегистрировать пустой массив в качестве значения по умолчанию для ключа «NewArray».

let defaultValues = ["NewArray": [String]()] 
UserDefaults.standard.register(defaults: defaultValues) 

В Второй VC определить newArray (имена переменных должны начинаться с буквы в нижнем регистре) также как пустые String массив

var newArray = [String]() 

В viewDidLoad извлечь массив из пользователей по умолчанию, добавлять новые , сохраните массив до значений по умолчанию пользователя и перезагрузите табличный вид

override func viewDidLoad() { 
    super.viewDidLoad() 

    let defaults = UserDefaults.standard 
    newArray = defaults.array(forKey: "NewArray") as! [String] 
    newArray.append(newItem) 
    defaults.set(newArray, forKey: "NewArray") 
    self.tableView?.reloadData() 
} 

beginUpdates(), endUpdates() и insertRowsAtIndexPath/reloadRowsAtIndexPaths не нужны вообще.

+0

Спасибо, что ваш код работает отлично и так легко понять. Спасибо снова .... – Joe

Смежные вопросы