ios Swift:获取 CoreData 作为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26524510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift: Fetch CoreData as Array
提问by TdoubleG
I want to fetch all Saved Data in the sqlite table.
我想获取 sqlite 表中的所有保存数据。
I'm currently doing this:
我目前正在这样做:
func GetAllData() -> NSArray
{
var error : NSError? = nil;
var request : NSFetchRequest = NSFetchRequest(entityName: "Locations");
let result : [AnyObject] = managedObjectContext!.executeFetchRequest(request, error:&error)!;
var elements : NSMutableArray = NSMutableArray();
for fetchedObject in result
{
elements.addObject(fetchedObject[0]);
}
print(elements);
return elements;
}
I have no problems to fetch Data in Objective-C but in swift I dont get it!
我在 Objective-C 中获取数据没有问题,但在 swift 中我不明白!
The saving of the data works fine. I have two rows "Name" and "Category". How can I show all saved data?
数据的保存工作正常。我有两行“名称”和“类别”。如何显示所有保存的数据?
回答by derdida
You should load all your Objects from CoreData into an Array/Dict of NSManaged Objects.
您应该将 CoreData 中的所有对象加载到 NSManaged 对象的数组/字典中。
For Example:
例如:
var locations = [Locations]() // Where Locations = your NSManaged Class
var fetchRequest = NSFetchRequest(entityName: "Locations")
locations = context.executeFetchRequest(fetchRequest, error: nil) as [Locations]
// Then you can use your properties.
for location in locations {
print(location.name)
}
回答by Vikram Biwal
Try this:
尝试这个:
let fetchRequest = NSFetchRequest(entityName: "Locations")
do {
let results = try managedObjectContext.executeFetchRequest(fetchRequest)
let Locations = results as! [Locations]
for location in Locations {
println(location)
}
} catch let error as NSError {
print("Could not fetch \(error)”)
}
回答by Abdul Karim
Swift 3
斯威夫特 3
func fetchData(){
onlyDateArr.removeAll()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "PhotoData")
do {
let results = try context.fetch(fetchRequest)
let dateCreated = results as! [PhotoData]
for _datecreated in dateCreated {
print(_datecreated.dateCreation!)
onlyDateArr.append(_datecreated)
}
}catch let err as NSError {
print(err.debugDescription)
}
}
回答by Fattie
2020 syntax
2020 语法
to copy and paste
复制和粘贴
func grabAllPersons() {
var pp: [CD_Person] = []
do {
let r = NSFetchRequest<NSFetchRequestResult>(entityName: "CD_Person")
let f = try core.container.viewContext.fetch(r)
pp = f as! [CD_Person]
} catch let error as NSError {
print("woe grabAllPersons \(error)")
}
for p: CD_Person in pp {
print(" >> \(p.firstName)")
}
}
Note that core.container.viewContext
is "your" context, often (but not always) the one supplied by core.container.viewContext
. (Example)
请注意,这core.container.viewContext
是“您的”上下文,通常(但不总是)由core.container.viewContext
. (示例)
In some cases it is ABSOLUTELYimportant you don't accidentally use the wrong context, when you are doing some incidental issue like counting or grabbing all the items. It is explained HEREunder the large heading "exercise extreme caution..."
在某些情况下,绝对重要的是不要意外使用错误的上下文,当你在做一些偶然的问题,比如计算或抓取所有项目时。据介绍这里的大标题下的“演习格外小心......”
回答by user9476144
import UIKit
import CoreData
class CoreDataHandler: NSObject {
private class func getContext() -> NSManagedObjectContext
{
let delegate = UIApplication.shared.delegate as? AppDelegate
return (delegate?.persistentContainer.viewContext)!
}
class func saveObeject (name:String,roll:String,college:String)
{
let context = getContext()
let entity = NSEntityDescription.entity(forEntityName: "CountryInfo", in: context)
let manageObjet = NSManagedObject(entity: entity!, insertInto: context)
manageObjet.setValue(name, forKey: "name")
manageObjet.setValue(roll, forKey: "roll")
manageObjet.setValue(college, forKey: "college")
do
{
try context.save()
}catch
{
print("unable to save data")
}
}
class func getCountryDetail(name:String) ->Array<Any>?
{
// return "http://1.bp.blogspot.com/-J9emWhBZ_OM/TtQgVQmBHRI/AAAAAAAAD2w/j7JJMRMiuAU/s1600/Al_Ain_FC.png"
let contecxt = getContext()
let fetchRequest:NSFetchRequest<CountryInfo> = CountryInfo.fetchRequest()
var user:[CountryInfo] = []
let predicate = NSPredicate(format: "name LIKE[cd] %@",name)
fetchRequest.predicate = predicate
do{
user = try contecxt.fetch(fetchRequest)
let ClubInfoBO = user
print(ClubInfoBO)
return (ClubInfoBO) as? Array<Any>
}catch
{
return nil
}
}
class func deleteObject(user:CountryInfo) ->Bool{
let context = getContext()
context.delete(user)
do
{
try context.save()
return true
}catch{
return false
}
}
//Clean delete
class func cleanDelete () ->Bool
{
let context = getContext()
let delete = NSBatchDeleteRequest(fetchRequest: CountryInfo.fetchRequest())
do{
try context.execute(delete)
return true
}catch
{
return false
}
}
}