在Java中,您可以使用以下方法获取非托管对象:
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
dogs = realm.where(Dog.class).lessThan("age", 2).findAll()
realm.commitTransaction();
realm.close()
如何使用Realm-cocoa在Swift中执行此操作?
答案 0 :(得分:8)
要从Swift中的Realm获取非托管对象,您可以使用init(value: AnyObject)
初始值设定项:
let unmanagedObject = Object(value: existingObject)
在你的代码示例中BTW你也没有得到一个非托管对象,你需要在Java中使用这样的东西:
RealmObject unmanagedObject = Realm.copyFromRealm(RealmObject existingObject)
在docs中查看更多内容。
答案 1 :(得分:0)
对于目标c,有助手类。 https://github.com/yusuga/RLMObject-Copying
非常老旧和过时-一个重要的解决方法是
- (instancetype)deepCopy {
Class objClass = [RLMSchema classForString:self.objectSchema.className];
RLMObject *object = [[objClass alloc] init];
for (RLMProperty *property in self.objectSchema.properties) {
if (property.array) {
RLMArray *thisArray = [self valueForKeyPath:property.name];
RLMArray *newArray = [object valueForKeyPath:property.name];
for (RLMObject *currentObject in thisArray) {
if ([currentObject isKindOfClass:[NSString class]]) {
[newArray addObject:(NSString*)[currentObject copy]];
}else if ([currentObject isKindOfClass:[NSNumber class]]) {
[newArray addObject:(NSNumber*)[currentObject copy]];
}else if ([currentObject isKindOfClass:[NSDate class]]) {
[newArray addObject:(NSDate*)[currentObject copy]];
}else if ([currentObject isKindOfClass:[NSData class]]) {
[newArray addObject:(NSData*)[currentObject copy]];
}else {
[newArray addObject:[currentObject deepCopy]];
}
}
}
else if (property.type == RLMPropertyTypeObject) {
RLMObject *value = [self valueForKeyPath:property.name];
[object setValue:[value deepCopy] forKeyPath:property.name];
}
else {
id value = [self valueForKeyPath:property.name];
[object setValue:value forKeyPath:property.name];
}
}
return object;
}