Swift 4 in Xcode 9 - 读取核心数据中的数据失败
Swift 4 in Xcode 9 - Read data in core data failed
我的函数read()有一个谓词不能正常工作,我设置了“no”0可以读取所有数据,如果我设置其他则不能。
class DataClass
{
private(set) var no: Int16?
private(set) var title: String?
private(set) var content: NSAttributedString?
init(no: Int16,
title: String,
content: NSAttributedString)
{
self.no = no
self.title = title
self.content = content
}
}
func read(no: Int16) -> DataClass?
{
let ReadData = DataClass()
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Note", in: managedObjectContext)
let request = NSFetchRequest<Note>(entityName: "Note")
request.fetchOffset = 0
request.entity = entity
print("noBtnDn: \(no)")
let predicate = NSPredicate(format: "no == %@", NSNumber(value: no))
request.predicate = predicate
do{
let results = try managedObjectContext.fetch(request)
print("results`count: \(results.count)")
for note in results
{
//ReadData.title = note.title!
//ReadData.content = (note.content as? NSAttributedString)!
ReadData.ReadFromNote(note: note)
print("no: \(note.no)")
}
}
catch{
print("Failed to read data.")
return nil
}
return ReadData
}
它打印 resultscount: 24* when no=0 (the count of all data is 24),print *results
count: 0 当 no!=0 时。数据的“no”没有0,都是从1开始的
所以当 no=0 时,打印
noBtnDn: 0
results` count: 24
no: 1
no: 2
no: 3
...
no: 24
不知道为什么找不到正确的“no”,是不是我的功能用错了?
您的 class 是否符合核心数据属性?
您是否也尝试过将可选的 Int16 变为非可选的?
我的函数read()有一个谓词不能正常工作,我设置了“no”0可以读取所有数据,如果我设置其他则不能。
class DataClass
{
private(set) var no: Int16?
private(set) var title: String?
private(set) var content: NSAttributedString?
init(no: Int16,
title: String,
content: NSAttributedString)
{
self.no = no
self.title = title
self.content = content
}
}
func read(no: Int16) -> DataClass?
{
let ReadData = DataClass()
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Note", in: managedObjectContext)
let request = NSFetchRequest<Note>(entityName: "Note")
request.fetchOffset = 0
request.entity = entity
print("noBtnDn: \(no)")
let predicate = NSPredicate(format: "no == %@", NSNumber(value: no))
request.predicate = predicate
do{
let results = try managedObjectContext.fetch(request)
print("results`count: \(results.count)")
for note in results
{
//ReadData.title = note.title!
//ReadData.content = (note.content as? NSAttributedString)!
ReadData.ReadFromNote(note: note)
print("no: \(note.no)")
}
}
catch{
print("Failed to read data.")
return nil
}
return ReadData
}
它打印 resultscount: 24* when no=0 (the count of all data is 24),print *results
count: 0 当 no!=0 时。数据的“no”没有0,都是从1开始的
所以当 no=0 时,打印
noBtnDn: 0
results` count: 24
no: 1
no: 2
no: 3
...
no: 24
不知道为什么找不到正确的“no”,是不是我的功能用错了?
您的 class 是否符合核心数据属性?
您是否也尝试过将可选的 Int16 变为非可选的?