2016-09-21 10 views
1

UITableViewから行を削除し、NSUserDefaultsから配列を更新する適切な方法はありますか?Swift/iOSのNSUserDefaultsからUITableViewと配列を更新する適切な方法

NSUserDefaultsから配列を読み取り、内容をUITableViewに送っていますが、ユーザーがUITableViewのアイテムを削除することも許可しています。読み書きするタイミングがわからないNSUserDefaultsに変更され、行が削除されるとすぐにテーブルが更新されます。ご覧のとおり、配列viewDidLoadの配列を読み込み、commitEditingStyleメソッドで再保存することから始めます。このメソッドを使用すると、行が削除されたときにテーブルが再ロードされません。

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Lets assume that an array already exists in NSUserdefaults. 
    // Reading and filling array with content from NSUserDefaults. 
    let userDefaults = NSUserDefaults.standardUserDefaults() 
    var array:Array = userDefaults.objectForKey("myArrayKey") as? [String] ?? [String]() 
} 

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = UITableViewCell() 
    cell.textLabel!.text = array[indexPath.row] 
    return cell 
} 

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
    if editingStyle == UITableViewCellEditingStyle.Delete { 
     array.removeAtIndex(indexPath.row) 
     tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) 
    } 
    // Save array to update NSUserDefaults  
let userDefaults = NSUserDefaults.standardUserDefaults() 
userDefaults.setObject(array, forKey: "myArrayKey") 


// Should I read from NSUserDefaults here right after saving and then reloadData()? 
} 

これは通常どのように処理されますか?

おかげ

答えて

1

は、基本的には正しいのですが、何かが削除されている場合にのみ、ユーザデフォルトに保存する必要があります。

if editingStyle == UITableViewCellEditingStyle.Delete { 
    array.removeAtIndex(indexPath.row) 
    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) 
    let userDefaults = NSUserDefaults.standardUserDefaults() 
    userDefaults.setObject(array, forKey: "myArrayKey") 
} 

アレイを読み込む必要はなく、推奨されません。

cellForRowAtIndexPathで、セルを再利用するには、Interface Builderで識別子を指定する必要があります。

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) 

データ・ソース・アレイはviewDidLoadに値を割り当て、テーブルビューをリロード次いで

var array = [String]() 

クラスのトップレベルで宣言されなければなりません。

override func viewDidLoad() { 
    super.viewDidLoad() 

    let userDefaults = NSUserDefaults.standardUserDefaults() 
    guard let data = userDefaults.objectForKey("myArrayKey") as? [String] else { 
     return 
    } 
    array = data 
    tableView.reloadData() 
} 
+0

ありがとうございました! –

関連する問題