hiragram no blog

iOSとか

Enums as configurationは別にアンチパターンでは無いのでは

ちょっと前の記事だけど。

Enums as configuration: the anti-pattern via @jesse_squires

この記事が言いたいのは

  • enumインスタンスの設定をするのは、提供された選択肢から選ぶしか無いので利用者側の自由度が低く良くない。
    • ライブラリやフレームワークがそうなっていると、選択肢を増やしたかったらPR投げてマージしてもらわないといけない。
  • Swiftのswitch文はenumを網羅しないとコンパイルエラーになるから、あちこちにエラーがでて悲しいからよくない。

ということらしい。

で、以下が僕の主張。

僕はパターンを網羅していないとコンパイル通してくれないSwiftのswitchは好きだ。同じ理由でenum使ってswitchするときにdefaultを使うのは嫌いだ。

Swift3の新しいアクセス修飾子について考察

3行で

  • Swift3から新たなアクセス修飾子 open,fileprivateが追加された
  • privateの扱いが変わった
  • ゆるい順に、open,public,internal,fileprivate,private

open

「モジュール外からアクセスでき、 サブクラス化(継承)可能である」ことを示すアクセス修飾子。以前まではpublicがこれを示していたが、publicは「モジュール外からアクセスできるが、 サブクラス化(継承)は出来ない」に変更された。

openはSwift2以前のpublicにあたり、Swift3のpublicはSwift2以前のpublicfinal修飾を付け足したもの?

fileprivate

「同じファイル内からのみアクセス可能である」ことを示すアクセス修飾子。Swift2以前のprivateと同じ。Swift3のprivateは、「定義されたスコープ内からのみアクセス可能」に変更された。

利用

openpublic、及びfileprivateprivateの使い方、使い分けについて考察する。

まず、Xcode8でできるSwift3のシンタックスへのコンバートをかけると、

  • publicはそのまま
  • privatefileprivate

になった。

近年Appleプロトコル指向プログラミング(Protocol Oriented Programming, POP)を推進しており

  • 参照型のクラスよりも値型の構造体を使いましょう(構造体は継承が無い)
  • 継承を使わずにプロトコルとエクステンションで実現しましょう

と考えているようで、コンバート時にpublicopenに置換されないのは「なるべく継承させないように作ろうね」というメッセージなのではと感じた。

privatefileprivateの使い分けについてはまだ考察中で、基本的にはprivateに寄せて参照できるスコープを狭くするべきだと思うが、一方でSwiftには

struct Human {
  var name: String
}

extension Human: HogeProtocol {
  func hogeMethod() {
    print("hoge")
  }
}

extension Human: FugaProtocol {
  func fugaMethod() {
    print(name)
  }
}

可読性の向上のためにプロトコルの実装をエクステンションとして切り出して書く派も存在し、もしプロパティnameprivateだった場合には2つのエクステンションからは参照できなくなる。

安全のためにスコープを狭くするべきか、可読性のために多少スコープの広がりを許容するかの問題だが、これはどちらを取るべきなんだろうか。

まとめ

基本的に自作の型でopenをたくさん使うとしたらライブラリ作者くらいであろう。Appleが継承地獄から脱却しようとしているのは明らかなので、それに沿う形で順応していこうと思う。

fileprivateについては、世間がどう受け止めるかという感じがするので、もうすこし様子を見たい。

参考

xibからビューのインスタンスを生成するコードの治安を良くする

AwesomeView.xibからAwesomeViewインスタンスを作りたい時、普通にUINibのイニシャライザを使って呼び出すと

let awesome = UINib(nibName: "AwesomeView", bundle: nil).instantiateWithOwner(nil, options: nil).first as! AwesomeView

こんなに治安が悪い。

  • nibNameを文字リテラルで指定している
  • force cast (as!)

この辺が治安を悪くしている。これをプロジェクト内のあちこちに撒き散らすのは本当にかなしくてみじめなことになるので、こんな方法を考えた。

まず「xibからインスタンス生成できる」という性質を示すプロトコルを作る。

protocol NibInstantiatable {
  // 上で言う、"AwesomeView"が入ってるプロパティ
  static var nibName: String { get }

  // そとから呼び出すメソッド
  static func instantiateFromNibWithOwner(ownerOrNil: AnyObject?, options: [NSObject: AnyObject]?) -> Self
}

次に、UIView用にデフォルト実装を持たせる。

extension NibInstantiatable where Self: UIView {
  static var nibName: String {
    get {
      // 上で言う"AwesomeView"みたいな、「自分のクラス名の文字列」を返す
      return String(Self.self)
    }
  }

  static func instantiateFromNibWithOwner(ownerOrNil: AnyObject?, options: [NSObject: AnyObject]?) -> Self {
    // 治安の悪いコードはここだけに閉じ込められる。
    return UINib(nibName: nibName, bundle: nil).instantiateWithOwner(ownerOrNil, options: options).first as! Self
  }
}

AwesomeView.swiftの変更は

- class AwesomeView: UIView {
+ final class AwesomeView: UIView, NibInstantiatable {

}

と、NibInstantiatableの指定をするだけ。protocolのメソッドでSelfを使っている都合からfinalの指定が必要になるが、ビュークラスの継承はしない、というルールが自分の中にあるので問題なし。

UIViewのサブクラスなのでこれでprotocol extensionに記載されたコードが実行される。 呼び出し側はこんな感じ。

let awesome = AwesomeView.instantiateFromNibWithOwner(nil, options: nil)

AwesomeViewのインスタンスを作っていることが一発でわかるし、

let awesome = UINib(nibName: "AwesomeView", bundle: nil).instantiateWithOwner(nil, options: nil).first as! AwesomeView

これと比べると随分治安がよくなったのではないだろうか。

このprotocol extensionの実装は、xibのファイル名が「クラス名.xib」の時だけ有効である。もし何らかの理由でクラス名とxib名が違うのであれば(リネームしろよ感はあるものの)、以下のように

final class AwesomeView: UIView, NibInstantiatable {
  static var nibName = "SuperAwesomeView"
}

nibNameだけ自分のクラスに書いてやれば、protocol extensionではなくこっちが優先されるのでこれも対応が楽。

iOSDCに参加した #iosdc

会場が練馬って朝知ったので遅刻した。

ベストトーク賞とられたReactive Programmingの話。

メモリ管理の話。

デザイナーにStoryboard使ってもらう話。

デバッグの話。

余談

追記

対応ありがとうございます。

さらに追記

うるせえ!!!!!!!!!!!!!!!!!!!!!!!

NSTextFieldをAutoLayoutで配置すると幅が0になっちゃう

最近趣味プログラミングでAppKitを触っている。

AppKitについて言いたいことはいろいろあるがUILabel代わりに使ったNSTextFieldについてハマったので書いておく。

Slackのメッセージみたいな見た目のビューを作りたくてAutoLayoutでごちゃごちゃ配置してたらNSTextFieldの幅がゼロになってしまって困った。
目指していた形はこんなの。

f:id:hiragram:20160818223139p:plain

で、当初ふつうに配置して制約かけたら

f:id:hiragram:20160818223944p:plain

こんなんなった。Xcodeのビューの階層見れるアレ(名前知らん)で見たらこんなん。

f:id:hiragram:20160818224014p:plain

いる。

幅0のNSTextField2つと、なんか中途半端に生き残ったNSTextFieldがいる。

最初に疑ったのはAutoLayoutで、自分で書けた制約のプライオリティとか、Content Compression Resistance Priorityなんかを気にしていろいろいじってみたが全然改善されず、1時間くらい浪費した。

Content Compression Resistance Priorityについて調べなおしていたら、intrinsicContentSizeにたどり着いた。

Custom views typically have content that they display of which the layout system is unaware. Setting this property allows a custom view to communicate to the layout system what size it would like to be based on its content. This intrinsic size must be independent of the content frame, because there’s no way to dynamically communicate a changed width to the layout system based on a changed height, for example.

つまりContent Compression Resistance Priorityで登場するビューの固有サイズというのはこいつのことらしい。かけられた制約が固有サイズより大きかった時の固有サイズの優先度がContents Hugging Priority、逆に制約が固有サイズより小さかった時の固有サイズの優先度がContents Compression Resistance Priorityということだ。

で、stringValueをセットしたあとのNSTextFieldのintrinsicContentSizeを見ると

自分でかけた制約に問題はなく、Content Compression Resistance Priorityにも問題はなく(そもそも触ってない)、AutoLayoutやめてsizeToFit()でサイズ決めて配置したとしてもintrinsicContentSizeのwidthは-1.0なので見えないままでしたよ、という結構きついハマりだった。

対応めんどくさかったら投げ出して帰るつもりだったが、StackOverflowにまさにその回答があった。

-[NSTextField intrinsicContentSize] always has undefined width - StackOverflow

この一番voteを稼いでる回答(というか質問者が自己解決したっぽい)によると、

OK, finally figured it out…

[_textfield setEditable:NO]

That's it. I guess that with an editable textfield one must have an explicit constraint for the textfield width. Which kind of makes sense, imagine editing a textfield and it would constantly grow horizontally with every keystroke... not an ideal UI.

僕はSwiftなので

nameLabel.editable = false

これでいけた。他のNSTextFieldも同じ。

Content Compression Resistance Priorityが具体的にどう動くのかを把握してなかったので時間くってしまった。

AutoLayoutに関して僕が良いなと思ったおすすめの本はこちら。

よくわかるAuto Layout  iOSレスポンシブデザインをマスター

よくわかるAuto Layout iOSレスポンシブデザインをマスター

いやーはまったはまった。

awakeFromNibのドキュメント読んだ

awakeFromNib

https://developer.apple.com/library/ios/documentation/UIKit/Reference/NSObject_UIKitAdditions/#//apple_ref/occ/instm/NSObject/awakeFromNib

ちゃんと理解してる自信がなかったので読んでみた。

Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file.

Interface Builder archiveもしくはnibファイルから読み込まれたあとに、サービスに必要なレシーバを用意します

The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the object in the archive have been loaded and initialized.

nib読み込み基盤はnib archiveから再生成されるオブジェクトが読み込まれ、初期化されたあとにawakeFromNibメッセージを送ります。

When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.

オブジェクトがawakeFromNibメッセージを受け取った時、そのオブジェクトのoutletとactionはすでに初期化されていることが保証されます。

You must call the super implementation of awakeFromNib to give parent classes the opportunity to perform any additiional initialization they require.

親クラスが必要とする初期化を実行するために、super classのawakeFromNibを呼びださなければいけません。

Although the default implementation of this method does nothing, many UIKit classes provide non-empty implementations.

このメソッドのデフォルト実装では何も処理されないが、多くのUIKitのクラスはこのメソッドで何らかの処理が行われている。

You may call the super implementation at any point during your own awakeFromNib method.

super classのawakeFromNibを呼び出すのは、自分のawakeFromNibメソッド内のどこでも良いです。

NOTE During Interface Builder's test mode, this message is also sent to objects instantiated from loaded Interface Builder plug-ins.

Because plug-ins link against the framework containing the object definition code, Interface Builder is able to call their awakeFromNib method when present.

The same is not true for custom objects that you create for your Xcode projects.

Interface Builder knows only about the defined outlets and actions of those objectsl it does not have access to the actual code for them.

このNOTEはまだ理解が追いついてないので省略

During the instantiation process, each object in the archive is unarchived and then initialized with the method befitting its type.

生成プロセスの間、archive内のそれぞれのオブジェクトはunarchiveされそれぞれの型にしたがって初期化されます。

Objects that conform to the NSCoding protocol (including all subclasses of UIView and UIViewController) are initialized using their initWithCoder: method.

NSCodingプロトコルに適合するオブジェクト(UIViewおよびUIViewControllerのすべてのサブクラスを含む)はinitWithCoder:メソッドによって初期化されます。

All objects that do not conform to the NSCoding protocol are initialized using their init method.

NSCodingプロトコルに適合しないオブジェクトはinitメソッドによって初期化されます。

After all objects have been instantiated and initialized, the nib-loading code reestablishes the outlet and action connections for all of those objects.

すべてのオブジェクトが生成され初期化されたあと、nib読み込みコードは再びそれらのオブジェクトのoutletとactionを有効にします。

It then calls the awakeFromNib method of the objects.

そしてそのオブジェクトのawakeFromNibをコールするのです。

For more detailed information about the steps followed during the nib-loading process, see Nib Files in Resource Programming Guide.

もっとnib読み込み処理の続きを知りたかったらResource Programming GuideのNib Filesの項を見てな。

IMPORTANT Because the order in which objects are instantiated from an archive is not guaranteed, your initialization methods should not send messages to other objects in the hierarchy.

オブジェクトがarchiveから生成される順番は保証されていないので、初期化メソッド(=イニシャライザ?)内で他のオブジェクトにメッセージを送るべきではありません。

Messages to other objects can be sent safely from within an awakeFromNib method.

awakeFromNibメソッド内では他のオブジェクトに安全にメッセージを送ることが出来ます。 (= 既に初期化が済んでることが保証されているから、かな)

Typically, you implement awakeFromNib for objects that require additional set up that cannot be done at design time.

一般に、デザイン時に出来ない (= xib上で出来ない?) セットアップをする処理をawakeFromNibに実装します。

For example, you might use this method to customize the default configuration of any controls to match user preferences or the values in other controls.

例えばこのメソッドを、あるコントロールのconfigurationをユーザー設定や他のコントロールの値によって決めたい時などに利用できます。

You might also use it to restore individual controls to some previous state of your application.

また、アプリケーションの過去の状態に応じてそれぞれのコントロールをリストアしたいときにも使うことが出来ます。