LoginSignup
13
10

More than 5 years have passed since last update.

RealmファイルをApp Groupで共有 / 削除

Last updated at Posted at 2016-03-14

App Extension等使っているとApp GroupでRealmファイルを共有したい場合があるかと思います。その手順をメモ。

まずは App GroupのコンテナのURLを取得

NSURL *containerPath = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.com.test"];

Realmのファイルパスを作る
好みによって、フォルダわけしてもいいかもしれない (Realm DBを消す際にフォルダ単位で消せるため )

[containerPath URLByAppendingPathComponent:@"test.realm"]

後は、用意したURLをRMLRealmConfigurationの+ (void)setDefaultConfiguration: でセットしてあげるだけ。以下、全コード

- (void)setupDB
{
    NSURL *containerPath = [[[NSFileManager defaultManager]
                            containerURLForSecurityApplicationGroupIdentifier:@"group.com.test"]
                            URLByAppendingPathComponent:@"test.realm"];

    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    config.path = containerPath.path;

    NSLog(@"Realm file path: %@", config.path);

    [RLMRealmConfiguration setDefaultConfiguration:config];
}

もちろん、他の箇所で[RLMRealm defaultRealm]を呼び出す前に呼んでください。


追記. Realmの削除

上記、Realmをフォルダにした場合は以下の方法で削除が可能です。 ( 公式のDocumentよりも簡単っぽい )。
[self realmFolderURL] はRealmフォルダのパスを示しています。

- (void)dropDB
{
    NSFileManager *manager = [NSFileManager defaultManager];
    NSError *error = nil;

    [manager removeItemAtURL:[self realmFolderURL] error:&error];

    if (error) {
        // error handling
        NSLog(@"error: %@", error);
    }
}

ちなみに、普通に削除する場合は公式を見ればよい

13
10
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
13
10