railsはmodelに色々便利にメソッドを定義できるが、Core Dataでもできないか調べてみた。
要約すると、Entityのsubclassをカテゴリーで拡張するというのがスタンダードらしいので、それをまとめます。
とりあえず、Xcodeでrojectのひな形としてMaster Detailsを選択し、core dataを使うにcheckを入れる。
出来たprojectをいじる。
-
NSManagedObject subclassを作成する。
New fileで
iOS > Xore Data > NSManagedObject subclass
を選択する。
すると、core_data_template.xcdatamodeld
で定義されたEvent entityを元にして、
Event.h
、Event.m
が作成される。Event.h
、Event.m
はcore_data_template.xcdatamodeld
を変更するたびに
上記の手順を踏んで作成し直す必要があるので、直接書き換えてはいけない。 -
カテゴリーを作成する。
New fileで
IOS > Cocoa Touch > Objective-C category
を選択する。
Categoryに「Formatter」と入力。
Category onに「Event」と入力。
すると、Event+Formatter.h
、Event+Formatter.m
が作成される。これをいじる!
-
カテゴリーを実装する。
一旦上記で作成したコードを表示する。
Event.h#import <Foundation/Foundation.h> #import <CoreData/CoreData.h> @interface Event : NSManagedObject @property (nonatomic, retain) NSDate * timeStamp; @end
Event.m#import "Event.h" @implementation Event @dynamic timeStamp; @end
Event+Formatterは実装済みのものです。
timeStampをformatして分のところだけを表示するようにしました。Event+Formatter.h@interface Event (Formatter) -(NSString *)formatted; @end
Event+Formatter.m#import "Event+Formatter.h" @implementation Event (Formatter) -(NSString *)formatted{ NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"mm"]; NSString *dateString = [formatter stringFromDate:self.timeStamp]; return dateString; } @end
-
MasterViewController.mでEvent+Formatterを呼び出す。
MasterViewController.mを適宜編集する。
これだけで、modelから自分で定義したmethodが呼び出せるようになります。MasterViewController.m#import "Event.h" //13行目あたり #import "Event+Formatter.h"
MasterViewController.m-(void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {//220行前後あたり // NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath]; // cell.textLabel.text = [[object valueForKey:@"timeStamp"] description]; Event *object = [self.fetchedResultsController objectAtIndexPath:indexPath]; cell.textLabel.text = [object formatted]; }
iOSのひな形
カテゴリーでメソッドを呼び出した版
フォーマットされて、分だけの表示になっている。