LoginSignup
28

More than 5 years have passed since last update.

tableView delegate/dataSourceを別ファイルにする場合のコツ

Posted at

目的:

 ViewControllerの肥大化抑制するため、tableViewのdelegate/dataSourceを別ファイルにします。そこで結構はまったので簡単にまとめておきます。

環境:

 Xcode 6.1.1

実装概要:

 StoryboardでtableViewを設置しておきます。delegate/dataSourceは別ファイルで実装します。ViewController内では実装しません。選択されたCellの中身はNotificationCenterで必要なところで拾うようにしておきます。

ソースコードと詳細説明:

 単純にdelegate/dataSourceを別ファイルで実装する場合は以下のようにして置き場問題ないです。

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

 tableSourceはdelegateとdataSourceを実装している別インスタンスで、別ファイルとなります。ここで重要なのは、そのばでインスタンスを作ってはいけないということです。optional関連のErrorがでます。
つまりどういうことかというと、

let tableSource = TableSource() --- Optional関連のErrorが発生する
self.tableView.delegate = self.tableSource
self.tableView.dataSource = self.tableSource

とすることです。
 回避策は以下のようにすると大丈夫でした。

sample.swift

import UIKit

class ViewController: UIViewController,
                    UITextFieldDelegate{

    // --- Outlets ---
    // MARK: Outlets
    @IBOutlet weak var tableView: UITableView!


    // --- Properties ---
    // MARK: Properties
    private var tableSource:tableSource!

    // いろいろな処理

    self.tableSource = tableSource() // initialize
    self.tableView.delegate = self.tableSource
    self.tableView.dataSource = self.tableSource

色々ためした結果このスタイルに落ち着きました。
何か他によい方法があったら教えてください。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28