如何创建自己的领域模型?

时间:2017-10-05 07:38:53

标签: ios objective-c realm

我正在尝试用目标C学习Realm模型。我想知道如何创建我们自己的.realm文件并在领域浏览器中查看领域文件。以下是我的代码。

-In Specimen.h

#import <Foundation/Foundation.h>
#import <Realm/Realm.h>

@interface Specimen : RLMObject//: NSObject
    @property NSString *name;
    @property NSString *specDescription;
    @property NSInteger latitude;
    @property NSInteger longitude;
    @property NSDate *date;
@end

-In UIViewController.m

#import "ViewController.h"
#import "Specimen.h"


@interface ViewController ()
{
    Specimen *first;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    first = [[Specimen alloc] init];

    first.name = @"first specimen";
    first.specDescription = @"some description";
    first.latitude = 12;
    first.longitude = 15;
    first.date = [NSDate date];

    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm transactionWithBlock:^{
        [realm addObject:first];
    }];

    NSLog(@"Object added in realm");
}

构建成功。最后一个日志也显示在控制台上。但我不明白在哪里可以看到Specimen对象,因为默认领域只有人和狗对象。 所以我需要知道如何创建自己的领域,然后添加对象并通过领域浏览器访问它。

1 个答案:

答案 0 :(得分:0)

来自境界official document

  

完成配置Realm文件存储位置的操作   通过   RLMRealmConfiguration

示例:

RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];

// Use the default directory, but replace the filename with the username
config.fileURL = [[[config.fileURL URLByDeletingLastPathComponent]
                      URLByAppendingPathComponent:username]
                      URLByAppendingPathExtension:@"realm"];

// Set this as the configuration used for the default Realm
[RLMRealmConfiguration setDefaultConfiguration:config];
  

您可以拥有多个配置对象,因此您可以控制   每个领域的版本,架构和位置:

RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];

// Get the URL to the bundled file
config.fileURL = [[NSBundle mainBundle] URLForResource:@"MyBundledData" withExtension:@"realm"];

// Open the file in read-only mode as application bundles are not writeable
config.readOnly = YES;

// Open the Realm with the configuration
RLMRealm *realm = [RLMRealm realmWithConfiguration:config error:nil];

// Read some data from the bundled Realm
RLMResults<Dog *> *dogs = [Dog objectsInRealm:realm where:@"age > 5"];