4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swift Xibファイルを使い始めるとloadNibNamedでexc_bad_access 落ちました

Posted at

お仕事の方のプロジェクトでは、
xibファイルがたくさん採用されたため、最近xibファイルを使い始めました。

xibファイルを追加するソースコードの箇所で落ちて、
EXC_BAD_ACCESSが発生してはまったのでメモしておきます。

Xcodeで新規ファイルを作成する時に、Viewを選択すると、xibファイルが生成、
Viewで必要なパーツをドラッグ、CocoaTouchClassでソースコードで書きます。

例えば、PlayerViewのxibファイル(Custom View)を作った。
同じ名前でCocoaTouchClassを作り、このようにコードを書きます。

class PlayerView: UIView {

    var playerLayer:AVPlayerLayer?
    @IBOutlet weak var timeLabel: UILabel!
        
    override func layoutSubviews() {
        super.layoutSubviews()
        playerLayer?.frame = self.bounds
    }

// 以下も書く場合があるようですが、これの有無による違いがよくわかりません。
//    override init(frame: CGRect) {
//        super.init(frame: frame)
//        loadFromNib()
//    }

    required public init?(coder aDecoder: NSCoder){
        super.init(coder: aDecoder)
        loadFromNib()
    }
    
    private func loadFromNib(){
        let view = Bundle.main.loadNibNamed("PlayerView", owner: self, options: nil)?.first as! UIView
        view.frame = self.bounds
        self.addSubview(view)
    }
}

そうすると、xibファイル(Interface)がcocoa touch class(ソースコード)と関連付できます。
しかし、ビルドしてみるとこの行

let view = Bundle.main.loadNibNamed("PlayerView", owner: self, options: nil)?.first as! UIView

でthread 1: exc_bad_access (code=2, address=0x7ffee5b3eff8)が発生して落ちました。
いろいろ記事を見ましたが、この記事が救ってくれました。

私の場合、原因がこれです!
FileOwnerをPlayerViewに設定し、
xigファイル内のViewのCustomClassも重ねてPlayerViewに設定してしまったからです。
Viewで重複設定した分外したら、落ちなくなりました。
スクリーンショット 2020-11-27 17.28.49.png

4
6
2

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
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?