我正在尝试向Core Data添加数据,我认为我已经走上正轨(我对此很新,所以,道歉)从下面的代码中,我的'Aim'是检查Core数据,如果为空则添加默认数据。
代码:
class func musicIsEmpty(managedObjectContext: NSManagedObjectContext)-> Bool{
let defaultMusic = NSEntityDescription.entityForName("Music", inManagedObjectContext: managedObjectContext)
let defaultMusicSetOne = NSManagedObject(entity: defaultMusic!, insertIntoManagedObjectContext: managedObjectContext) as? Music
//defaultMusicSetOne = NSManagedObject(entity: defaultMusic!, insertIntoManagedObjectContext: managedObjectContext) as? Music
let fetchRequest = NSFetchRequest(entityName: "Music")
fetchRequest.entity = defaultMusic
defaultMusicSetOne!.uri = "spotify:track:1puJlKuYGH58SAFgXREUpE"
defaultMusicSetOne!.duration = 30.0
defaultMusicSetOne!.starttime = 49.0
defaultMusicSetOne!.xfade = 10.0
defaultMusicSetOne!.voiceover = "1.25s Next Up.mp3"
do{
if let MusicSetResults = try managedObjectContext.executeFetchRequest(fetchRequest) as? [NSManagedObject]{
if MusicSetResults == 0
{
defaultMusic!.setValue(defaultMusicSetOne?.uri, forKey: "uri")
defaultMusic!.setValue(defaultMusicSetOne?.duration, forKey: "duration")
defaultMusic!.setValue(defaultMusicSetOne?.starttime, forKey: "starttime")
defaultMusic!.setValue(defaultMusicSetOne?.xfade, forKey: "xfade")
defaultMusic!.setValue(defaultMusicSetOne?.voiceover, forKey: "voiceover")
return true
}
else
{
return false
}
}
}
catch let error as NSError{
print("Error: \(error.debugDescription)")
}
return false
}
Music.Swift:
extension Music {
@NSManaged var voiceover: String?
@NSManaged var xfade: NSNumber?
@NSManaged var duration: NSNumber?
@NSManaged var starttime: NSNumber?
@NSManaged var uri: String?
}
但是我一直收到错误“这个类不是密钥uri的密钥值编码兼容”我确信这将适用于所有.setValues。我不确定为什么会出现这种情况,因为defaultMusic确实有“uri”字段,而defaultMusic也是音乐对象的实例。 .setValue的格式是错误的吗?还是别的什么?
任何帮助都会很棒!
提前致谢!!
答案 0 :(得分:2)
我怀疑你的确是这个意思:
检查实体是否为空,如果是,则插入具有默认值的新对象
class func musicIsEmpty(managedObjectContext: NSManagedObjectContext)-> Bool {
let musicEntity = NSEntityDescription.entityForName("Music", inManagedObjectContext: managedObjectContext)!
let fetchRequest = NSFetchRequest()
fetchRequest.entity = musicEntity
do {
let musicSetResults = try managedObjectContext.executeFetchRequest(fetchRequest) as! [Music]
if musicSetResults.isEmpty
{
let defaultMusicSetOne = NSManagedObject(entity: musicEntity, insertIntoManagedObjectContext: managedObjectContext) as! Music
defaultMusicSetOne.uri = "spotify:track:1puJlKuYGH58SAFgXREUpE"
defaultMusicSetOne.duration = 30.0
defaultMusicSetOne.starttime = 49.0
defaultMusicSetOne.xfade = 10.0
defaultMusicSetOne.voiceover = "1.25s Next Up.mp3"
return true
}
}
catch let error as NSError{
print("Error: \(error.debugDescription)")
}
return false
}
您也可以考虑保存托管对象上下文以使新对象持久化。
答案 1 :(得分:0)
defaultMusic
是NSEntityDescription
,而不是Music
对象。
(有时让Swift使用默认数据类型会让人感到困惑。)