CoreData Swift:如何保存和加载数据?

我正在Swift中编写iOS游戏,我想在最后添加一个高分标签。 我认为保存function是正确的,但负载一是给我带来问题的。 我已经创建了一个实体(“BestScores”)和属性(“classicBestScoreTF”):

要保存高分:

var bestscore25 = 1000 var score: int func savescore() { var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate) var context:NSManagedObjectContext = appDel.managedObjectContext! var score25: AnyObject! = NSEntityDescription.insertNewObjectForEntityForName("BestScores", inManagedObjectContext: context) as NSManagedObject score25.setValue(score, forKey: "classicBestScoreTF") context.save(nil) } func loadscore() { var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate) var context:NSManagedObjectContext = appDel.managedObjectContext! bestScore25 = valueForKey("classicBestScoreTF") as Int } func endgame() { if score > bestScore25 { savescore() loadscore() bestScoreLabel.text = "Best Score: \(bestScore25)" } if score < bestscore { loadscore() bestScoreLabel.text = "Best Score: \(bestScore25)" } } 

它不工作:(请帮忙!

保存数据:

 var person = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: self.managedObjectContext!) as Person person.name = "Mary" person.age = Float(arc4random() % 100) var error : NSError? = nil if !self.managedObjectContext!.save(&error) { NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } 

加载数据中:

 var error: NSError? = nil var fReq: NSFetchRequest = NSFetchRequest(entityName: "Frases") fReq.predicate = NSPredicate(format: "id contains[c] %@", String(day)) var sorter: NSSortDescriptor = NSSortDescriptor(key: "id" , ascending: false) fReq.sortDescriptors = [sorter] fReq.returnsObjectsAsFaults = false let result : [AnyObject] = self.managedObjectContext!.executeFetchRequest(fReq, error:&error)! 

为了保存数据,您应该使用:

 context.insertNewObjectForEntityForName(...) 

加载数据时也一样,应该是:

context.valueForKey(…)

但是,我不确定这是否是正确的语法,因为您可能需要获取实体数组,然后获取索引0处的对象。那么为什么您使用核心数据获得高分? 您可能希望查看用户默认值或icloud,核心数据是针对数据库设计的

针对swift进行了更新:

用于加载,插入,删除日期的简单代码;

 import UIKit import CoreData class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate{ // MARK:- Variable Declarations @IBOutlet weak var mTableView: UITableView! var manageObjectContext: NSManagedObjectContext! var eventArray = [Event]() // MARK:- ViewController LifeCycle Methods override func viewDidLoad() { super.viewDidLoad() self.title = "Event Reminder" manageObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext self.loadSaveData() } override func viewWillAppear(_ animated: Bool) { // Remove empty cell from tableview mTableView.tableFooterView = UIView(frame: .zero) } // MARK:- TableView DataSource and Delegate Methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return eventArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ViewControllerTableViewCell")! as! ViewControllerTableViewCell cell.layer.cornerRadius = 05 let eventArrayItem = eventArray[indexPath.row] if let eventImage = UIImage(data: (eventArrayItem.event_image! as Data)){ cell.mImageView.image = eventImage } cell.mEventHeadingLabel.text = eventArrayItem.event_heading cell.mShortDescriptionLabel.text = eventArrayItem.event_description return cell } // To delete Particular cell/row from tableview func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { let eventArrayItem = eventArray[indexPath.row] if editingStyle == .delete { manageObjectContext.delete(eventArrayItem) do { try manageObjectContext.save() } catch let error as NSError { print("Error While Deleting Note: \(error.userInfo)") } } self.loadSaveData() } // MARK:- IBAction Methods @IBAction func actionOnPlusButton(_ sender: Any) { let imagePicker = UIImagePickerController() imagePicker.sourceType = .photoLibrary imagePicker.delegate = self self.present(imagePicker, animated: true, completion: nil) } // MARK:- ImagePicker Delegate Methods func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let mImage = info[UIImagePickerControllerOriginalImage] as? UIImage{ picker.dismiss(animated: true, completion: { self.createEventItemWith(selectedImage: mImage) }) } } // MARK:- Instance Methods func createEventItemWith(selectedImage: UIImage) { let eventItem = Event(context: manageObjectContext) let alertController = UIAlertController(title: "Add Event", message: "Enter event and it's description", preferredStyle: .alert) let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in let eventNameTextField = alertController.textFields![0] as UITextField let descriptionTextField = alertController.textFields![1] as UITextField print("firstName \(String(describing: eventNameTextField.text)), secondName \(String(describing: descriptionTextField.text))") if eventNameTextField.text != "" || descriptionTextField.text != ""{ eventItem.event_heading = eventNameTextField.text eventItem.event_description = descriptionTextField.text eventItem.event_image = NSData(data: UIImageJPEGRepresentation(selectedImage, 0.3)!) do{ try self.manageObjectContext.save() self.loadSaveData() }catch{ print("Could not save data: \(error.localizedDescription)") } }else{ self.showAlertMessageToUser(title: "Alert", messageToUser: "Fields should not be empty, Please enter given info...") } }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (action : UIAlertAction!) -> Void in self.manageObjectContext.reset() }) alertController.addTextField { (textField : UITextField!) -> Void in textField.placeholder = "Enter event Name" } alertController.addTextField { (textField : UITextField!) -> Void in textField.placeholder = "Enter event description in short" } alertController.addAction(saveAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } func showAlertMessageToUser(title: String, messageToUser: String) { let alert = UIAlertController(title: title, message: messageToUser, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } func loadSaveData() { let eventRequest: NSFetchRequest = Event.fetchRequest() do{ eventArray = try manageObjectContext.fetch(eventRequest) self.mTableView.reloadData() }catch { print("Could not load save data: \(error.localizedDescription)") } } } 

在此处输入图像描述

  var sections = Dictionary>() var sortedSections = [String]() lazy var lazyImage:LazyImage = LazyImage() var restObject: [NSManagedObject] = [] var catObject: [NSManagedObject] = [] func callAPI(){ { //access token :- https://graph.facebook.com/search?type=place&fields=name,picture&center=22.9962,72.5996&access_token=EAAHP0nRkO90BAPEAo05HTR76NIKdEbuPqZAnY9ErjGMpZCZA2HynQ5MqWzwLeHrWElEUzTzRA497ZBuqBjxFl8qppZAJ4KlecIZBs8f6z4LPvofkJBtlxbpZBL0YiZBZBogv17pxtzEs8GvNdtvfldwwT487nHHPlz9PxZC4Pg0NaeuhPQTPQuAmHSGREyCld4KjYZD let apiStr = "http://158.69.124.80:82/api/GetRestaurantList?latitude=0.3476&longitude=32.5825" let session = URLSession.shared var url = URLRequest(url: URL(string: apiStr)!) url.setValue("amx 4d53bce03ec34c0a911182d4c228bb6c:I9oA4EezLVP4gV2PexrJS+rNp4vxLqP4x4hwhLYIi8Q=:b91647defdbd4af789b6b1e435447c74:guestuser@guestuser.com", forHTTPHeaderField: "Authorization") let task = session.dataTask(with: url) { (data, response, error) -> Void in if let data = data { do{ let jsonObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any] if jsonObject != nil{ self.deleteAllData() if let restaurants = jsonObject!["Data"] as? [[String:Any]]{ for i in 0.. 0{ for j in 0..(entityName: "Restaurants") do { restObject = try managedContext.fetch(fetchRequest) } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } let fetchRequest1 = NSFetchRequest(entityName: "Category") do { catObject = try managedContext.fetch(fetchRequest1) self.sections.removeAll() self.sortedSections.removeAll() for i in 0.. 

}

 *************extension********** extension NSDictionary{ func getStringValue(key : String) -> String { if let any : AnyObject = self.object(forKey: key) as AnyObject? { if let number = any as? NSNumber{ return number.stringValue }else if let str = any as? String{ return str } } return "" } func getArrayValue(key : String) -> NSArray { if let any : AnyObject = self.object(forKey: key) as AnyObject? { if let number = any as? NSArray{ return number } } return NSArray() } 

}

 *********image fatch************ if info.image.count > 0{ // self.image = jsonData.getArrayValue(key: "photos") if let imageInfo = info.image.object(at: 0) as? NSDictionary{ let url = imageInfo.getStringValue(key: "photo_reference") let combineString = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=\(url)&key=AIzaSyAVOo64abZw3yCaOCalZ_bLg2bDY51yRuI" cell.imgProfile.imageFromUrl(combineString) } } ************************CELL PRINT*************** let restSection = self.sections[self.sortedSections[indexPath.section]] let restaurant = restSection![indexPath.row] if let name = restaurant.name{ cell.lblName.text = name } if let location = restaurant.location{ cell.lblAddress.text = location } if let cuisines = restaurant.cuisines{ cell.lblMenu.text = cuisines } *********************fb login code************************************ 

让loginManager = LoginManager()

  loginManager.logIn(readPermissions: [.publicProfile,.email], viewController : nil) { loginResult in switch loginResult { case .failed(let error): print(error) case .cancelled: print("User cancelled login") case .success(let grantedPermissions, let declinedPermissions, let accessToken): self.returnUserData() print("Logged in") } } ****************** let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "first_name, email, last_name, picture"]) graphRequest.start(completionHandler: { (connection, result, error) -> Void in if ((error) != nil) { // Process error print("Error: \(String(describing: error))") } else { print(result ?? 123) }