CoreData: error: Failed to call designated initializer on NSManagedObject class 'Video'

时间:2016-07-11 22:20:24

标签: swift core-data

I'm currently getting the core data error and an 'unrecognized selector sent to instance #'. I can't seem to figure out what is happening. Here's the code.

import UIKit
import Alamofire

protocol FetchResultsControllerDelegate {
func dataReady()
}

class PNSClient: NSObject {

var pnsVideos = [Video]()
var delegate: FetchResultsControllerDelegate?

func getFeedVideos() {

    // Fetch the videos dynamically through the YouTube Data API
    Alamofire.request(.GET, Constants.YouTubeURL, parameters: [Parameters.Part: Parameters.Snippet, Parameters.PlaylistId: Constants.UPLOADS_PLAYLIST_ID, Parameters.Key: Constants.API_KEY, Parameters.MaxResults : 50], encoding: .URL, headers: nil)
        .validate()
        .responseJSON { (response) -> Void in

        switch response.result {
        case .Success(let JSON):
            print("Success with JSON: \(JSON)")

            let response = JSON as! NSDictionary
            let userID = response.objectForKey("items")
            print(userID)

        case .Failure(let error):
            print("Request failed with error: \(error)")
        }

        if let JSON = response.result.value {

            var arrayOfPNSVideos = [Video]()

            for video in JSON["items"] as! NSArray {
                print(video)

                let videoObj = Video()
                videoObj.videoId = video.valueForKeyPath("snippet.resourceId.videoId") as? String
                videoObj.videoTitle = video.valueForKeyPath("snippet.title") as? String
                videoObj.videoDescription = video.valueForKeyPath("snippet.description") as? String
                if let highUrl = video.valueForKeyPath("snippet.thumbnails.high.url") as? String {
                    videoObj.videoThumbnailUrl = highUrl

                arrayOfPNSVideos.append(videoObj)
            }

            self.pnsVideos = arrayOfPNSVideos

            if self.delegate != nil {
                self.delegate?.dataReady()
                }
        }
    }
}

If looking at the repo will help: www.github.com/pbellot77/pop-nutshell

1 个答案:

答案 0 :(得分:1)

要将对象存储到CoreData中,您需要遵循以下模式。我建议您在CoreData或tutorial上阅读docs

let entity = NSEntityDescription.entityForName("Video", inManagedObjectContext: managedObjectContext!) 
// you need to make sure you have a reference to your CoreData managedObjectContext
    let videoObj = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContext!) as? Video
    videoObj.property1 = "some value"
    videoObj.videoId = video.valueForKeyPath("snippet.resourceId.videoId") as? String

// etc ...


do {
    try managedObjectContext!.save()
}
catch {
    print("Error saving video changes: \(error)")
}