如何使用Objective C在Realm DB中存储数组值(RLMArray)?

时间:2017-03-15 10:30:15

标签: ios objective-c realm

如何在Realm DB中存储数组值(RLMArray)?

我的.h文件,

 @interface Hotlines : RLMObject
 @property (strong, nonatomic) NSString  *id;       
 @property (strong, nonatomic) NSString *department_name;
 @property (strong, nonatomic) NSString *flag;
 @property (strong,nonatomic) RLMArray<Numbers> *numbers;   
 @end

2 个答案:

答案 0 :(得分:3)

您需要为Numbers数组创建领域模型:

#import <Realm/Realm.h>

// Define your models for Numbers array
@interface Numbers : RLMObject
@property NSInteger *num;
@property (strong, nonatomic) NSString *name;
@end
RLM_ARRAY_TYPE(Numbers) // define RLMArray< Numbers >


// Define your models for Numbers array
@interface Hotlines : RLMObject
@property (strong, nonatomic) NSString  *id;       
@property (strong, nonatomic) NSString *department_name;
@property (strong, nonatomic) NSString *flag;
@property (strong,nonatomic) RLMArray<Numbers> *numbers;   
@end

// Implementations
@implementation Numbers
@end // none needed

@implementation Hotlines
@end // none needed

有关更多信息,请参阅Realm Objective c

更新

 RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
       Hotlines *obj = [[Hotlines alloc] init]; 
       obj.department_name = @"anyString";
        Numbers *number = [[Numbers alloc] init]
        number.num = 1;
      [obj.numbers addObject:number] 
      [realm addObject:obj];
}];

对于多个数据:

[realm transactionWithBlock:^{
    Hotlines *obj = [[Hotlines alloc] init];
    obj.department_name = @"anyString";

    for (int i=0; 1< 10; i++) {
        Numbers *number = [[Numbers alloc] init]
        number.num = i;
        number.name = @"XYZ"
        [obj.numbers addObject:number]
    }
    [realm addObject:obj];
}];

答案 1 :(得分:0)

如果只需要数字,可以使用基元来完成:

@interface Hotlines : RLMObject
@property NSString *id;       
@property NSString *department_name;
@property NSString *flag;
@property RLMArray<NSNumber*><RLMFloat> *numbers;
@end

realm docs

  

RLMArrays可以存储原始值来代替Realm对象。在   为此,请使用以下任一约束RLMArray   协议:RLMBool,RLMInt,RLMFloat,RLMDouble,RLMString,RLMData,   或RLMDate