在两个对象中发送带有引用和更新值的自定义对象:iOS

Send custom object with reference and update values in both object: iOS

我需要将引用 class 中的值更新到我的自定义单元格。

我要归档:

  1. 从API获取数据//已完成
  2. 从 API 创建自定义对象(模型) // 已完成
  3. 将对象引用发送到数组中的自定义单元格
  4. 更改自定义单元格中的值
  5. 更新视图控制器数组中的值

我读了这个link但无法更新值

https://medium.com/@abhimuralidharan/difference-between-value-type-and-a-reference-type-in-ios-swift-18cb5145ad7a

https://developer.apple.com/swift/blog/?id=10

下面是我的class

class Post {
    // https://www.raywenderlich.com/9481-reference-vs-value-types-in-swift
    var objPost:ObjPost

    init(_ objPost:ObjPost) {
        self.objPost = objPost
    }
}

struct ObjPost:Codable {
    var id:Int
    var contentAvailable : Bool
    var userId : Int
    var userName : String
    var userProfileImage: String
    var subTitle : String
    var postedSince : String
    var isPin : Bool
    var location : String
    var lat : String
    var long: String
    var isLiked: Bool
    var isDisliked : Bool
    var likes : Int
    var dislikes: Int
    var shares: Int
    var comments:Int
    var description: String
    var albumId: Int
    var privacy: Int
    var isEditable: Bool
    var media:[ObjMedia]
}

struct ObjMedia:Codable {
    var id: Int
    var type: Int // 1 = Image, 2=Video
    var url: String
    var description: String?
    var thumb: String
    var isLiked: Bool
    var isDisliked:Bool
    var likes:Int
    var dislikes: Int
    var shares: Int
    var comments: Int
    var isEditable:Bool
    var isPin: Bool
    var isCoverMedia: Bool
}

传递对象的引用 ObjPost tableView: UITableView, cellForRowAt indexPath: IndexPath

In below code get reference object from array with -1 value indexPath.row-1, Because 1st row is fix UI in my project requirement.

cell.objPostDetails = Post(arrPosts[indexPath.row-1].objPost)

自定义单元格代码和

var objPostDetails:Post! // Create object variable.

更新自定义单元格中的值代码

self.objPostDetails.objPost.isLiked  = !self.actionSelected // Here is action selected is bool variable
self.objPostDetails.objPost.isDisliked  = self.actionSelected // Here is action selected is bool variable

我的问题是更新单元格中的值而不是更新数组中的值 当我上下滚动时,旧值可见。

此外,将 ObjPostObjMedia 作为 class 而不是 struct。然后一切都按预期进行。

class ObjPost:Codable {
    var id:Int
    var contentAvailable : Bool
    var userId : Int
    var isDisliked : Bool
 ...
}

class ObjMedia:Codable {
    var id: Int
    var type: Int
    var url: String
    var description: String?
...
}