ios - 如何将一对多关系对象分配给变量?

标签 ios swift core-data

对令人困惑且可能不准确的标题表示歉意。

无论如何,我有两个 CoreData 实体。列表和评论。一个列表可以有多个注释,因此实体模型反射(reflect)了这一点。

extension Listing {

    @NSManaged var listingTitle: String?
    @NSManaged var comments: NSSet?
}

extension Comment {

    @NSManaged var comment: String?
    @NSManaged var commentId: String?
    @NSManaged var rating: Int32
    @NSManaged var username: String?
    @NSManaged var listing: Listing?

}

在应用程序中的某个时刻,我想用注释填充 UITableView,但这样做有点困难。

var listing: Listing?

override func viewDidLoad() {
    super.viewDidLoad()

    //I assumed I could do this
    var comments: [Comment] = [Comment]()
    comments = listings?.comments // This throws an error saying NSSET cant be assigned to type [Comment]

有人可以指导我完成我在这里想做的事情的正确方法吗?我可以看到这个问题与以下事实有关:在 Listing 实体中,注释被定义为未定义类型的 NSSet,因此我可能无法将该 NSSet 直接分配给 Comment 数组。

谢谢!

最佳答案

您可以访问上面的列表 -> 评论,如下所示。

override func viewDidLoad() {
        super.viewDidLoad()

        var listing = Listing()

        //Assign listing coredata object according to your values and save it.


        //Fetch above listing comments in array format and use it according to your requirement.

        var listingComments:Array = listing.comments!.allObjects
        let commentFirst:Comment = listingComments[0] as! Comment
        print(commentFirst.commentId)
        print(commentFirst.comment)
        print(commentFirst.rating)
        print(commentFirst.username)
    }   

listingComments类似于你声明的变量'var comments:[Comment]',你不需要显式地写[Comment],你可以通过它的allObjects属性访问NSSet对象并将其分配给Array对象。

关于ios - 如何将一对多关系对象分配给变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35056757/

相关文章:

ios - 带操作按钮的 UILocalNotification

swift - 有没有办法避免使用 Xcode 8 将 Swift 从 2.2 转换为 2.3 或 3?

iphone - iPhone 中的核心数据默认使用哪个持久存储

objective-c - NSManagedObject子类和xcdatamodeld文件之间有什么关系?

ios - ... 处的 bundle 包含不允许的文件 'Frameworks'

ios - 如何从本周的工作日名称获取具体日期

ios - UICollectionView 自定义布局问题与 layoutAttributesForElementsInRect :rect

ios - NSDateformatter dateFromString AnyObject

ios - 仅当设备连接到 MacBook 时后台应用程序才工作时的 didReceiveRemoteNotification

cocoa - 将 CoreData 与对象一起使用?