Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

cocoa

realm

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 ?

like image 473
David Avatar asked Aug 18 '16 08:08

David


2 Answers

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.

like image 132
Dmitry Avatar answered Oct 21 '22 21:10

Dmitry


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;
}
like image 24
Alex Avatar answered Oct 21 '22 20:10

Alex