LoginSignup
26
25

More than 5 years have passed since last update.

はじめてのRealm

Posted at

昨日 http://realm.connpass.com/event/13652/ に行ってきました。
いや、すいません、難しかった。RxJavaとか。

超魅力的なRealmですが「ちょっとRealm使ってみようかな〜〜」っていう甘い考えで参加した人(=自分)とかは挫折しそうな勢いで難しかった。後々超参考になる日が来るだろうけど。(来るといいな)

というわけで、そんな人(=自分)が挫折しないような、実際に動くコードを書いてみた。
サンプルのディレクトリを見たら絶対同じのがあると確信したけど、どれだけ簡単に使えるかというのを確認したかったので、 http://realm.io/jp/docs/cocoa/ だけ見て書いてみました。

いや、なんかもう、いろいろ良くしてもらっている人が前に立っていたにも関わらず「いまさらかよ!」と言われそうですが、すいません。

・右上の「+」で今のDateを取得して追加
・左上の「Del.All」で全件削除
・タップしたセルのDate更新
・セルスワイプからの削除でその項目削除

StoryboardでNavigationController追加して、TableViewに下記のコード突っ込んで貰えれば動くはず。CellのIdentifierはdefaultCellで。

このコードはDBとして一番の醍醐味と言っても過言ではない検索とかソートとかも使ってないので、本格的な使い方には程遠いけど、NSArray と NSDictionary が使えれば Realm のさわりは使えるというサンプルだと思って頂ければ。

というわけで、TableViewController そのままどーん。

#import "RealmTableViewController.h"
#import <Realm.h>

@interface RealmTableViewController ()
@end

//======================================================
@interface MyItem : RLMObject
@property (nonatomic, retain) NSDate* date;
@end

@implementation MyItem
@end

//======================================================

@implementation RealmTableViewController

- (void)addItemAndReload {
    MyItem* item = [MyItem new];
    item.date = [NSDate date];
    [RLMRealm.defaultRealm beginWriteTransaction];
    [RLMRealm.defaultRealm addObject:item];
    [RLMRealm.defaultRealm commitWriteTransaction];
    [self.tableView reloadData];
}

- (void)deleteAllAndReload {
    [RLMRealm.defaultRealm beginWriteTransaction];
    [RLMRealm.defaultRealm deleteAllObjects];
    [RLMRealm.defaultRealm commitWriteTransaction];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addItemAndReload)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Del.All" style:UIBarButtonItemStylePlain target:self action:@selector(deleteAllAndReload)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    RLMResults* items = [MyItem allObjects];
    return items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"defaultCell" forIndexPath:indexPath];

    RLMResults* items = [MyItem allObjects];
    MyItem* item = [items objectAtIndex:indexPath.row];
    cell.textLabel.text = item.date.description;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [RLMRealm.defaultRealm beginWriteTransaction];
    RLMResults* items = [MyItem allObjects];
    MyItem* item = items[indexPath.row];
    item.date = [NSDate date];
    [RLMRealm.defaultRealm commitWriteTransaction];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source

        [RLMRealm.defaultRealm beginWriteTransaction];
        RLMResults* items = [MyItem allObjects];
        MyItem* item = [items objectAtIndex:indexPath.row];
        [RLMRealm.defaultRealm deleteObject:item];
        [RLMRealm.defaultRealm commitWriteTransaction];

        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
}

@end

今まで作ったアレとかアレとか、Realm 使って書き直したいな。と思ったのでした。

26
25
0

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
26
25