0

What's the correct way to instantiate an RLMObject with an array of other RLMObjects?

The docs don't mention anything and my initial attempts (do nothing, assume Realm does the right thing and create an empty array and assign that when I set my first relationship up don't seem to work.

Here's my code:

[[RLMRealm defaultRealm] beginWriteTransaction];
[_realmAnswers removeAllObjects];
NSMutableArray* newArray = [NSMutableArray arrayWithCapacity:answers.count];

for (NSString* answerString in answers){
    OFEAnswerEntry* newAnswer = [[OFEAnswerEntry alloc] init];
    newAnswer.answerString = answerString;
    [newArray addObject:newAnswer];
}

[_realmAnswers addObjectsFromArray: newArray];
[[RLMRealm defaultRealm] commitWriteTransaction];

2 Answers 2

3

Using the addObjectsFromArray: method on RLMArray:

ArrayPropertyObject *obj = [ArrayPropertyObject createInRealm:realm withObject:@[@"arrayObject", @[], @[]]];
StringObject *child1 = [StringObject createInRealm:realm withObject:@[@"a"]];
StringObject *child2 = [[StringObject alloc] init];
child2.stringCol = @"b";
[obj.array addObjectsFromArray:@[child2, child1]];

This code was taken directly from a unit test in realm-cocoa.

You could also do this in fewer lines of code:

NSArray *stringObjects = @[
    [[StringObject alloc] initWithObject:@[@"a"]],
    [[StringObject alloc] initWithObject:@[@"b"]]
];
[ArrayPropertyObject createInRealm:realm withObject:@[@"arrayObject", stringObjects, @[]]];
Sign up to request clarification or add additional context in comments.

Comments

1

So jpsim's answer is the correct way to add objects but the problem in my code (added since his answer) is that RLMArray properties are created lazily from the accessor on first reference and using underscore ivar notation (_realmAnswers) avoids that load.

Changing my code from:

[_realmAnswers addObjectsFromArray: newArray];

to

[self.realmAnswers addObjectsFromArray: newArray];

Fixes the problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.