无法在TableViewCell内的UILabel中显示来自CoreData的Double

时间:2015-08-10 13:02:13

标签: ios swift core-data

在这个表视图(override func tableView)中,我显示了兴趣点,一些是默认加载的,另一些是用户加载的。我可以检索托管对象的名称,但是当尝试显示位置时,它会失败。

我无法在TableViewCell中显示纬度和经度。如果我使用name关键字,则会显示名称。也许我应该从数字做某种转换,但在哪里?

我也收到了这个警告:

  

CoreData:警告:无法为实体“ArcheoPOI”加载名为“PRODUCT_MODULE_NAME.ArcheoPOI”的类。找不到类,而是使用默认的NSManagedObject。

这是我的NSManagedContext

enter image description here

import UIKit
import CoreData

import CoreLocation

class AppiaTVC: UITableViewController, UITableViewDataSource, UITableViewDelegate {


    var places : [NSManagedObject] = []

    let myLocationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        //MARK : good way to set the reuse id of the cell
        //        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") //alternative to put it in the
        //MARK : good way to set the table title
        title = "\"All the POI\""


    }





    //MARK: - Added for fetching data from CoreData
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        //1
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

        let managedContext = appDelegate.managedObjectContext!      //needed to handel mangedObject (saving and fetching entries)

        //2
        let fetchRequest = NSFetchRequest(entityName:"ArcheoPOI")

        //3
        var error: NSError?

        let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject]

        if let results = fetchedResults {
            places = results
        } else {
            println("Could not fetch \(error), \(error!.userInfo)")
        }
    }




    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return places.count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("appiaCellID", forIndexPath: indexPath) as! AppiaTVCell

        cell.backgroundColor = UIColor.blueColor()
        if indexPath.row % 2 == 0 {
            //            cell.backgroundColor = UIColor(red: 143 / 255, green: 204 / 255, blue: 255 / 255, alpha: 1)
            //            cell.sweetTextView.backgroundColor = UIColor(red: 63 / 255, green: 159 / 255, blue: 255 / 255, alpha: 1)

        } else {
            //            cell.backgroundColor = UIColor(red: 63 / 255, green: 159 / 255, blue: 255 / 255, alpha: 1)
            //            cell.sweetTextView.backgroundColor = UIColor(red: 143 / 255, green: 204 / 255, blue: 255 / 255, alpha: 1)
        }


        let singlePlace = places[indexPath.row]
        //KVC is the only way to access data in CoreData (can't use a property) butwe could also use a more natural object-style person.name
        //        cell.textLabel!.text = singlePlace.valueForKey("name") as? String
        cell.cellNameLabel.text = singlePlace.valueForKey("name") as? String
        cell.cellLatitudeLabel.text = singlePlace.valueForKey("latitude") as? String //if I use "name" it works
        cell.cellLongitudeLabel.text = singlePlace.valueForKey("longitude") as? String //if I use "name" it works

        return cell
    }




    @IBAction func addPlaceButtonPressed(sender: UIBarButtonItem) {

        var alert = UIAlertController(title: "New place", message: "Add a new place", preferredStyle: .Alert)

        let saveAction = UIAlertAction(title: "Save", style: .Default) { (action: UIAlertAction!) -> Void in

            let textField = alert.textFields![0] as! UITextField
            self.saveName(textField.text) //self.names.append(textField.text)
            self.tableView.reloadData()
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction!) -> Void in
        }

        alert.addTextFieldWithConfigurationHandler {
            (textField: UITextField!) -> Void in
        }

        alert.addAction(saveAction)
        alert.addAction(cancelAction)

        presentViewController(alert,
            animated: true,
            completion: nil)

    }




    //MARK: - save data to CoreData - this function is called by the addName button
    func saveName(name: String) {
        //1
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

        let managedContext = appDelegate.managedObjectContext!

        //2
        let entity =  NSEntityDescription.entityForName("ArcheoPOI", inManagedObjectContext: managedContext)   //NSEntityDescription is required

        let place = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)


        myLocationManager.startUpdatingLocation()
        let lat = myLocationManager.location.coordinate.latitude
        let lon = myLocationManager.location.coordinate.longitude
        myLocationManager.stopUpdatingLocation()
        println("************************")
        println(lat)
        println(lon)
        println("************************")


        //3
        place.setValue(name, forKey: "name")
        place.setValue(lat, forKey: "latitude")
        place.setValue(lon, forKey: "longitude")

        //4
        var error: NSError?
        if !managedContext.save(&error) {

            println("Could not save \(error), \(error?.userInfo)")

        }
        //5
        places.append(place)
    }




    //MARK - delete NSManagedObject
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

        switch editingStyle {

        case UITableViewCellEditingStyle.Delete:
            // remove the deleted item from the model
            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            let managedContext:NSManagedObjectContext = appDelegate.managedObjectContext!


            managedContext.deleteObject(places[indexPath.row] as NSManagedObject)
            places.removeAtIndex(indexPath.row)

            managedContext.save(nil)

            //tableView.reloadData()
            // remove the deleted item from the `UITableView`
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

        default:
            return

        }
    }




    @IBAction func BackButtonPressed(sender: UIBarButtonItem) {

        dismissViewControllerAnimated(true , completion: nil)

    }


}

2 个答案:

答案 0 :(得分:0)

这是针对你提到的CoreData警告:

在.xcdatamodeld文件中查看实体时,请打开Utilities标签,然后查看Data Model inspector部分。 Module有一个下拉列表。对于一些较新的Xcode 7测试版,它默认会显示Current Product Module。删除它并将其留空。这应该可以解决你的问题。

答案 1 :(得分:0)

将您的代码更改为

let latitude = singlePlace.valueForKey("latitude")
let longitude = singlePlace.valueForKey("longitude")
cell.cellLatitudeLabel.text = "\(latitude)" //if I use "name" it works
cell.cellLongitudeLabel.text = "\(longitude)" //if I use "name" it works

我也强烈建议您创建一个管理您实体的课程。您可以找到有关如何执行此操作的良好说明here。本教程是Objective-c,但从那以后没有什么变化太多;)

然后,您就可以拨打singlePlace.latitutde而不是使用valueForKey