Download - 俺のManaged Objectの使い方は間違っていた
俺のManaged Objectの使い方は間違っていた
iOS_LT#12 on 2014.4.23 佐藤 新悟
NSManagedObject
• Core Dataで管理されるモデルオブジェクト
• そのまま使っても良いけど、属性にvalueForKey:とかでアクセスしないといけない
• 通常サブクラスでpropertyを定義して使う
intとかBOOLにNSNumberを 使わなくてもいい
やりがちなこと
// interface @property (nonatomic, strong) NSNumber *flag;
// implementation - (BOOL)flagValue { return [self.flag boolValue]; } !- (void)setFlagValue:(BOOL)value { self.flag = @(value); }
スカラープロパティを使う
スカラープロパティを使う
// interface @property (nonatomic, assign) BOOL flag; !// implementation @dynamic flag;
やることはこれだけ!
スカラープロパティを使う• Appleのドキュメントにスカラー値を使う場合アクセサは自前で実装しろと書いてあるがこれは古い記述
• XcodeにやらせるとNSDateまでNSTimeintervalになるが気に入らなければNSDateに直せばいい
• スカラーとオブジェクトの変換コストはもちろんある。コレクションに入れたりするならNSNumberのままもあり。
属性で扱えないオブジェクトも 自前で変換処理を書かなくていい
やりがちなこと// interface !// attribute @property (nonatomic, strong) NSString *colorString; // attributeじゃない @property (nonatomic, strong) UIColor *color; !!// implementation - (UIColor *)color { UIColor *color = nil; // self.colorString のカラーコードからUIColorを作る return color; } !- (void)setColor:(UIColor *)color { NSString *colorString = nil; // UIColorからカラーコードの文字列を作る self.colorString = colorString; }
Transformableを使う
// interface @property (nonatomic, strong) UIColor *color; !// implementation @dynamic color;
やることはこれだけ!
Transformableを使う• NSCodingに準拠したオブジェクトはすべて同様に扱える
• 裏でNSValueTransformerが値を変換している
• カスタムのvalue transformerを定義すればNSCoding
じゃないどんなオブジェクトも扱える。
※標準の属性タイプのいずれかに変換できれば
entityの継承関係とクラスの 継承関係は一致してなくていい
よくある設計
Animal
Cat Human
Animal
Cat Human
Entity Class
NSManagedObject
EntityとClassは独立に設計可能
Animal Cat HumanAnimal
Cat Human
Entity Class
NSManagedObject
BaseManagedObject
EntityとClassは独立に設計可能• Entityを継承するとDB上ではひとつの大きなテーブルができるので、データの持ち方として効率的ではない
• すべてのManaged Objectで共通にやりたいことをBaseサブクラスに書いて、Entityに対応するクラスはそれを継承する、といったことが可能
まとめ• スカラー値のプロパティを使うにはプリミティブ型で宣言するだけでOK
• NSCoding準拠のオブジェクトはTransformable
を使おう
• Entityの階層とClassの階層は独立に設計できる
参考URL
• Core Dataでスカラー値をプリミティブ型のプロパティで扱う方法 -
Qiitahttp://qiita.com/gonsee/items/4daff9c7c86e8cae836b
• Data Models and Model Objects - Core Data - objc.io issue #4http://www.objc.io/issue-4/core-data-models-and-model-objects.html
• Core Data Programming Guide: Non-Standard Persistent Attributeshttps://developer.apple.com/library/ios/documentation/cocoa/conceptual/CoreData/Articles/cdNSAttributes.html#//apple_ref/doc/uid/TP40001919-SW1