【问题标题】:Realm- updating all items in array of objects instead of appending only new one领域 - 更新对象数组中的所有项目,而不是仅附加新项目
【发布时间】:2016-08-01 03:03:34
【问题描述】:

我正在尝试在 JournalEntryVC.swift 中添加与患者相关的不同日记条目。

My Patient 类有一个日记条目数组,即let journalEntries = List<Journal>() My Journal 类有代表日记条目属性的属性,即entryTypeentryDateentryCaption

但是,当循环访问 JournalEntryVC.swift 中的 json 时,不仅将新的日记条目对象附加到日记条目数组newPatient.journalEntries.append(myJournal),我之前附加的日记条目的属性也被最新的日记条目属性替换.

例如,newPatient.journalEntries[0] 具有与 newPatient.journalEntries[1] 相同的 entryCaptionentryType 字符串值等。

主要问题:关于如何添加新的日记帐分录及其属性但不更改先前附加日记帐分录的日记帐分录属性的任何想法?

谢谢!

//  Patient.swift

import Foundation
import RealmSwift


class Patient: Object {
    
    dynamic var patientName = ""
    dynamic var patientAvatar = ""
    dynamic var patientId = 0
    dynamic var isDietitian = false 

//array of journal entries for each patient
    let journalEntries = List<Journal>() 

    
    override class func primaryKey() -> String {
        return "patientId"
    }
}

//  Journal.swift

import Foundation
import RealmSwift


class Journal: Object {

    dynamic var entryId = ""
    dynamic var entryType = ""
    dynamic var entryImg = ""
    dynamic var entryCaption = ""
    dynamic var entryComment = ""
    dynamic var entryCategory = ""
    dynamic var entryDate = ""
   
     
    override class func primaryKey() -> String {
        return "entryId"
    }
  
}

//JournalEntryVC.swift

import UIKit
import Alamofire
import BXProgressHUD
import SwiftyJSON
import RealmSwift


class JournalEntryVC: UIViewController, UITableViewDelegate, UITableViewDataSource {


  func reloadInitialData ( ) {
    
    //mutable arrays containing journal entry attributes
    desc.removeAllObjects()
    type.removeAllObjects()
    category.removeAllObjects()
    metric_stat.removeAllObjects()
    entryImages.removeAllObjects()
    dateCreate.removeAllObjects()
    comments.removeAllObjects()
    entryType.removeAllObjects()
    id.removeAllObjects()
    //comments.removeAllObjects()
    content.removeAllObjects()
    patName.removeAllObjects()
    
    
    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
    dispatch_async(dispatch_get_global_queue(priority, 0)) {
        let request = Alamofire.request(.GET, "https://gethealthie.com/entries.json", headers: [
            "access-token": userCreds.objectForKey("access-token")! as! String,
            "client": userCreds.objectForKey("client")! as! String,
            "token-type": userCreds.objectForKey("token-type")! as! String,
            "uid": userCreds.objectForKey("uid")! as! String,
            "expiry": userCreds.objectForKey("expiry")! as! String
            ]).responseJSON { response in
                
                print(response.response)
                
                let json = JSON(data: response.data!)
                
                
                if json.count == 0 {
                    BXProgressHUD.hideHUDForView(self.view);
                }else {
                    
                    //Realm- create object instances of Patient and Journal class
                    let newPatient = Patient()
                    let myJournal = Journal()
                    
                    for i in 0 ..< json.count {
                        
                        let entry = json[i]
                        print(entry)
                        
                        let name = entry["entry_comments"]
                        let k = name["id"]
                        
                        //add entry attributes to mutable arrays
                        self.type.addObject(entry["type"].stringValue)
                        self.desc.addObject(entry["description"].stringValue)
                        self.category.addObject(entry["category"].stringValue)
                        self.metric_stat.addObject(entry["metric_stat"].stringValue)
                        self.dateCreate.addObject(entry["created_at"].stringValue)
                        self.comments.addObject(entry["entry_comments"].rawValue)
                        self.entryType.addObject(entry["category"].stringValue)
                        let posterInfo = entry["poster"]
                        let first = posterInfo["first_name"].stringValue
                        let last = posterInfo["last_name"].stringValue
                        let full = first + " " + last
                        self.patName.addObject(full)
                        self.id.addObject(entry["id"].stringValue)
                        self.entryImages.addObject(entry["image_url"].stringValue)
                        
                        
                        //Realm- access properties in Journal class and set it equal to the current journal entry attribute i.e. json[i]
                        myJournal.entryType = entry["type"].stringValue
                        myJournal.entryCaption = entry["description"].stringValue
                        myJournal.entryCategory = entry["category"].stringValue
                        myJournal.metricStat = entry["metric_stat"].stringValue
                        myJournal.entryDate = entry["created_at"].stringValue
                        //  myJournal.entryComment = entry["entry_comments"].rawValue as! String
                        
                        //append a NEW journal entry to the array of journal entries in Patient class i.e. let journalEntries = List<Journal>() as the json loops thru different journal entries
                        newPatient.journalEntries.append(myJournal)
                        
                        if i == json.count - 1 {
                            // do some task
                            dispatch_async(dispatch_get_main_queue()) {
                                self.tableView.reloadData()
                                BXProgressHUD.hideHUDForView(self.view)
                            }
                        }
                        
                    }
                    
                    //Realm- add newPatient object instance to realm
                    try! self.realm.write {
                        self.realm.add(newPatient)
                        
                    }
                }
                
        }
    }
  }

}

【问题讨论】:

    标签: ios arrays swift persistence realm


    【解决方案1】:

    您在 for 循环之外实例化 Journal 的单个实例,更改该 Journal 的值,然后将其附加到患者的 journalEntries。尝试在 for 循环中移动 let myJournal = Journal()

    【讨论】:

    • 非常感谢您的帮助!我是 Swift 和 Realm 的新手,所以你把我推向了正确的方向。此外,我注意到数据在启动之间没有持久化。根据 Realm 文档,您必须在写入事务中将对象添加到 Realm 中才能使其持久存在,我相信我在上面这样做了。是否还有其他原因导致它在两次启动之间没有持续存在(即在强制退出应用程序并再次启动后)?
    • 这可能是因为您在后台线程中执行写入但使用self.realm,我猜这是在主线程上实例化的。您可以简单地执行let realm = try! Realm() 并使用该对象在您的线程中进行写入。这里有更详细的讨论:realm.io/docs/swift/latest/#threading
    • 澄清一下,即使在飞行模式下强制退出然后在飞行模式下再次启动它(不确定这是否是一个有效的用例)后,我也试图保留数据。虽然数据持续存在,并且当我启动应用程序(使用 wifi)并切换到飞行模式时,我能够使用领域对象显示它,但在我强制退出它(在飞行模式下)后它似乎并没有持续存在并以飞行模式再次启动它。我尝试let realm = try! Realm() 按照您的建议在我自己的线程中编写,但似乎不适用于我的用例。
    猜你喜欢
    • 2023-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 2022-01-19
    相关资源
    最近更新 更多