封装的核心数据对象

时间:2018-12-30 05:17:21

标签: ios swift core-data persistence encapsulation

我有一个保存在核心数据中的json数据,并将其保存在一个数组中,并且我想封装保存在核心数据中的数组。问题是当我想在应用程序中显示它时,它仅检索数组中的1个数据。假设我有一个5.在这里,我显示我的代码

这是我的函数获取请求我的json数据

APIServices.shared.fetchData(url: APIServices.youtubeBaseURL, params: params, of: Item.self) { (items) in
            let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
            privateContext.parent = CoreDataManager.shared.persistenceContainer.viewContext

            var newVideos = [Video]()
            items.forEach({ (item) in
                let video = Video(context: privateContext)
                video.title = item.snippet.title
                video.videoId = item.id.videoId

                newVideos.append(video)

                do {
                    try privateContext.save()
                    try privateContext.parent?.save()

                } catch let saveErr {
                    print("Failed to save json data:", saveErr)
                }
            })
            DispatchQueue.main.async {
                self.videos = newVideos
                self.collectionView.reloadData()
                self.showLoadingHUD()
            }
        }

这是我封装在collectionViewCell中的代码

var video: Video? {
    didSet{
        let context = CoreDataManager.shared.persistenceContainer.viewContext
        let fetchRequest = NSFetchRequest<Video>(entityName: "Video")

        do {
           let videos = try context.fetch(fetchRequest)
            videos.forEach { (video) in
                titleLabel.text = video.title
                guard let videoId = video.videoId else { return }
                DispatchQueue.main.async {
                    let playerVars: [String : Any] = [
                        "playsinline" : 0,
                        "enablejsapi": 1,
                        "wmode": "transparent",
                        "controls": 1,
                        "showinfo": 0,
                        "rel": 0,
                        "modestbranding": 1,
                        "iv_load_policy": 3 //annotations
                    ]
                    self.player.load(withVideoId: videoId, playerVars: playerVars)
                }
            }
        } catch let fetchErr {
            print("Failed to fetch video:", fetchErr)
        }
    }
}

获取核心数据并尝试在videos.print中打印视频后,每个值不仅只有一个值。但是当我尝试加载youtube播放器时,它只会显示一个值。

only one object return

1 个答案:

答案 0 :(得分:1)

对于您的解决方案,

在您的videoModel类中创建一个UICollectionViewCell变量,并删除引起问题的fetchRequest类中的UICollectionViewCell调用,

var videoModel: VideoModel? {
        didSet {
            titleLabel.text = videoModel?.videoTitle
            let playerVars: [String : Any] = [
                "playsinline" : 0,
                "enablejsapi": 1,
                "wmode": "transparent",
                "controls": 1,
                "showinfo": 0,
                "rel": 0,
                "modestbranding": 1,
                "iv_load_policy": 3 //annotations
            ]
            self.player.load(withVideoId: videoModel?.videoId ?? "", playerVars: playerVars)
        }
    }

ViewModel文件应该看起来像

import Foundation

struct VideoModel {
    var videoTitle: String?
    var videoId: String?

    init(title: String, id: String) {
        videoTitle = title
        videoId = id
    }
}

然后在SearchViewController中创建一个viewModels数组,并在videoModel数据源方法中为您的单元格分配cellForItemAt

var videoModels = [VideoModel]()

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: videoId, for: indexPath) as! SearchVideoCell

        let video = videos[indexPath.row]
        cell.delegate = self
        cell.video = video
        cell.videoModel = videoModels[indexPath.row]

        return cell
    }

最后在fetchVideosWith中将viewModel附加到您的viewModels数组中,

//MARK:- Fetch Data
    fileprivate func fetchVideosWith(title name: String) {
        let params = ["part": "snippet", "q": "tausiyah \(name)", "key": "AIzaSyC2mn0PTL8JmSWEthvksdJLvsnwo5Tu9BA"]

            APIServices.shared.fetchData(url: APIServices.youtubeBaseURL, params: params, of: Item.self) { (items) in
                let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
                privateContext.parent = CoreDataManager.shared.persistenceContainer.viewContext

                var newVideos = [Video]()
                items.forEach({ (item) in
                    let video = Video(context: privateContext)
                    video.title = item.snippet.title
                    video.videoId = item.id.videoId

                    newVideos.append(video)

                    do {
                        try privateContext.save()
                        try privateContext.parent?.save()
                    } catch let saveErr {
                        print("Failed to save json data:", saveErr)
                    }
                    let videoModel = VideoModel(title: item.snippet.title, id: item.id.videoId)
                    self.videoModels.append(videoModel)
                })
                DispatchQueue.main.async {
                    self.videos = newVideos
                    self.collectionView.reloadData()
                    self.showLoadingHUD()
                }
            }
    }

希望有帮助。