2016-09-20 5 views
1

配列が空でUITableViewまたはUIPickerViewから要求を出したときのクラッシュを防ぐには?UITableViewで初期化されていない配列を安全に使用し、空のテーブルを表示するにはどうすればいいですか?

私の現在の方法は、ダミーデータで使用する前に常に配列を初期化することですが、ダミーデータは必要ない場合もあり、時にはそれが意味をなさないこともあるため、実際にデータを表示するには、ほとんどの場合、データがない場合は空のテーブルを表示します。例えば

私は普通続くようAppDelegateでそれを初期化UITableViewに使用するNSUserDefaultsから配列を取得する場合は...

AppDelegate.swift:

NSUserDefaults.standardUserDefaults().registerDefaults([ 
     keyMyAarray:["Dummy Data"]// initializing array 
    ]) 

SomeViewController:再び

var myArray = read content from NSUserDefaults... 

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

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

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

、どのように私は無事 UITableViewで初期化されていない配列を使用して空のテーブルを表示することができますか?

+2

あなたの 'myArray'に要素がない場合、間違いなく空のテーブルが表示されます! 'numberOfRowsInSection'の' return myArray.count'は – Lion

+1

を保証します。 – NSNoob

+0

これでアプリがクラッシュすることはありませんか?私は、初期化されていない配列の使用に起因するエラー/クラッシュを見ました。 –

答えて

3

"ダミーデータ"を配列に配置する必要はありません。空の配列を初期化することができます。以下のように

var myArray = [String]() 

numberOfRowsInSection return myArray.countにあります。 countが0の場合、cellForRowAtIndexPathは呼び出されず、あなたは安全に行くことができます。

1

デフォルトでは空の行が3つあります。

var myArray:Array<String>? = ... 

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

fun tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return myArray?.count ?? 3 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {   
    var cell = UITableViewCell() 
    if let arrayStrings = myArray, arrayStrings.count > indexPath.row { 
     cell.textLabel.text = arrayStrings[indexPath.row] 
    } 
    return cell 
} 
+0

空の行を追加することができます。ありがとう –

関連する問題