まーぽんって誰がつけたの?

iOS→Scala→インフラなおじさん技術メモ

SwiftでClassを作るときにNSObjectを継承するべき?

どっちを採用するべき?

class Animal {}
// or 
class Animal: NSObject {}

こっちのにしておけばとりあえず間違いないとか、こっちを使うとこんな時に困るとかそういう指針が知りたい。

よさそうな回答

stackoverflow.com

  • NSObjectを採用する時

  • Nativeクラスでいいとき

Swift classes that are subclasses of NSObject:

  • are Objective-C classes themselves
  • use objc_msgSend() for calls to (most of) their methods
  • provide Objective-C runtime metadata for (most of) their method implementations

Swift classes that are not subclasses of NSObject:

  • are Objective-C classes, but implement only a handful of methods for NSObject compatibility
  • do not use objc_msgSend() for calls to their methods (by default)
  • do not provide Objective-C runtime metadata for their method implementations (by default)

Subclassing NSObject in Swift gets you Objective-C runtime flexibility but also Objective-C performance. Avoiding NSObject can improve performance if you don't need Objective-C's flexibility.

With Xcode 6 beta 6, the dynamic attribute appears. This allows us to instruct Swift that a method should use dynamic dispatch, and will therefore support interception.

public dynamic func foobar() -> AnyObject {}

Objective-CからSwiftを利用するときには必ずNSObjectをみたいな話

stackoverflow.com

No need for NSObject. Just say public init() {}. – matt Feb 15 at 5:24

これ見るとそんなことする必要ないよって書いてある。

まとめ

native classのままでその方がパフォーマンスがよさそう。なので基本的にNSObjectを継承しない方向で必要な場合は継承するっていうスタンスでOKぽい。