David
David

Reputation: 195

How can I get unmanaged object from Realm query in Swift?

In Java, you can get unmanaged objects with this:

Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
dogs = realm.where(Dog.class).lessThan("age", 2).findAll()
realm.commitTransaction();
realm.close()

How can I do this in Swift with Realm-cocoa ?

Upvotes: 7

Views: 5347

Answers (2)

Alex
Alex

Reputation: 159

for objective c there are helper classes. https://github.com/yusuga/RLMObject-Copying

very old and outdated - an important fix would be

- (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;
}

Upvotes: 1

Dmitry
Dmitry

Reputation: 7340

To get an unmanaged object from Realm in Swift you can use init(value: AnyObject) initializer:

let unmanagedObject = Object(value: existingObject)

BTW in your code sample you don't get an unmanaged object as well, you need to use something like this in Java:

RealmObject unmanagedObject = Realm.copyFromRealm(RealmObject existingObject)

See more in docs.

Upvotes: 7

Related Questions