swift couchebase lite CBLModel document properties not saved

502 Views Asked by At

I try to create CBLModel object and save it in couchbase lite. The document saved without error, but when retrieve document from database the properties of a document is always nil.

// model

class TestModelUser: CBLModel {
    var userName:NSString?
}

// create and save

let userModel:TestModelUser = TestModelUser(newDocumentInDatabase: db)
userModel.userName = "test user name 10"
userModel.setValue(NSStringFromClass(TestModelUser), ofProperty: "type")
let saved = userModel.save(&error)
if saved {
    println("saved")
}else{
    if let err:NSError = error {
        println(err.localizedDescription)
    }
}

// retrive

let dbView:CBLView = db.viewNamed("userView")
dbView.setMapBlock({ (document, emit) -> Void in
    emit(document["_id"], document)
    if let docType = document["type"] as? String {
        if docType == NSStringFromClass(TestModelUser) {
            emit(document["_id"], document)
        }
    }
    }, version: "5")

let queryResult1:CBLQueryEnumerator = db.viewNamed("userView").createQuery().run(&error)
for row:CBLQueryRow in queryResult1.allObjects as [CBLQueryRow] {
    let user:TestModelUser = TestModelUser(forDocument: row.document)
    if let uName = user.userName {
        println(uName)
    }
}

and user.userName is always nil, maybe there is another way to save document?

1

There are 1 best solutions below

0
On

Solved.

Document property should have @NSManaged modifier:

class UserModel: CBLModel {
    @NSManaged var userName:NSString?
}

Thanks to jens (https://forums.couchbase.com/t/swift-couchebase-lite-save-cblmodel-document-problem/2054).