2016-03-18 101 views
1

例如嵌套的數組,我有兩個類:領域正在改寫,而不是更新的對象

class Message : Object { 

    dynamic var text_ : String = "" 

    convenience init(text: String) { 

     self.init() 
     text_ = text 
    } 

    override static func primaryKey() -> String? { 
     return "text_" 
    } 

} 

class UserProfile : Object { 

    dynamic var username_ : String = "" 

    var messages = List<Message>() 

    convenience init(username: String) { 
     self.init() 
     username_ = username 
    } 

    override static func primaryKey() -> String? { 
     return "username_" 
    } 

} 

所以我已經得到了用戶和他的一切消息列表,我想有能力更新列表時,我從什麼地方得到新的用戶配置實例:

let realm = try! Realm() 

let user1 = UserProfile(username: "user1") 
let message1 = Message(text: "message1") 
user1.messages.append(message1) 

try! realm.write { 

    realm.add(user1, update: true) 
} 
let results1 = realm.objects(UserProfile) 

print("Before updating: \(results1[0].messages)") 

let theSameUser = UserProfile(username: "user1") 
let message2 = Message(text: "message2") 
theSameUser.messages.append(message2) 

try! realm.write { 

    realm.add(theSameUser, update: true) 
} 
let results2 = realm.objects(UserProfile) 

print("After updating: \(results2[0].messages)") 

輸出是:

Before updating: List<Message> (
    [0] Message { 
     text_ = message1; 
    } 
) 
After updating: List<Message> (
    [0] Message { 
     text_ = message2; 
    } 
) 

但應包含兩條消息,在「更新後」中,因爲只存在一個用戶。我該怎麼做?

更新: 在文檔中有Realm示例。我的例子中,唯一的區別,就是境界的對象列表:這裏

// Creating a book with the same primary key as a previously saved book 
let cheeseBook = Book() 
cheeseBook.title = "Cheese recipes" 
cheeseBook.price = 9000 
cheeseBook.id = 1 

// Updating book with id = 1 
try! realm.write { 
realm.add(cheeseBook, update: true) 
} 
If a Book object with a primary key value of ‘1’ already existed in the database, then that object would simply be updated. If it did not exist, then a completely new Book object would be created and added to the database." 

回答

3

問題似乎是,境界不知道theSameUser實際上是相同的用戶爲第一用戶的代碼塊被執行之前因爲你是將用戶添加到這裏的境界:

try! realm.write { 
    realm.add(theSameUser, update: true) 
} 

的,其結果是,當你說

theSameUser.messages.append(message2) 

theSameUser.messages實際上是空的。所以如果你想追加一條消息到「user1」,你應該從Realm中獲取它,然後追加新的消息。

+0

這個。當您希望新用戶與舊用戶相同時,新用戶不與任何領域相關聯。因此它們還不平等。 – Andreas

+0

我已經使用了primaryKey來避免這種情況,文檔說:「如果你的模型類包含主鍵,你可以使用Realm()智能地更新或添加基於主鍵值的對象add(_:更新:)「。 –

+0

是的,但財產'消息'已更新爲'[message2]' – Andreas

相關問題