将对象添加到 RLMArray?

Adding objects to RLMArray?

我有类

//Ingredient.h
@interface Ingredient : RLMObject

@property (nonatomic, copy, readwrite) NSString *name;

@end

RLM_ARRAY_TYPE(Ingredient)

//Recipe.h
@interface Recipe : RLMObject

@property (nonatomic, strong, readwrite) RLMArray<Ingredients *>< Ingredients> *ingredients;

@end

添加多种成分正确吗?

Ingredient *tomato = [[Ingredient alloc] init];
tomato.name = @"tomato";
Ingredient *onion = [[Ingredient alloc] init];
onion = @"onion";

Recipe *recipe = [[Recipe alloc] init];

[realm beginWriteTransaction]
[recipe.ingredients add:tomato];
[recipe.ingredients add:onion];
[realm.commitWriteTransaction];

还有其他办法吗?

关闭! RLMArray 遵循 NSMutableArray 的方法命名约定。

所以正确的方法名是

[realm beginWriteTransaction]
[recipe.ingredients addObject:tomato];
[recipe.ingredients addObject:onion];
[realm.commitWriteTransaction];

查看 RLMArray's documentation 以获得您可以使用的方法的完整列表。例如,一种更简化的添加对象的方法可能是:

[realm beginWriteTransaction]
[recipe.ingredients addObjects:@[tomato, onion]];
[realm.commitWriteTransaction];