2016-02-09 87 views
1

我在从核心数据加载信息(位置)时遇到问题,我的核心数据[商店]有lat(纬度)和long(经度)两列。但不能加载到MapView。MapKit从核心数据加载位置

import UIKit 
    import MapKit 
    import CoreData 

    class allMapPinsViewController: UIViewController, MKMapViewDelegate { 

var shop: [Shops]! = [] 

var appDelegate: AppDelegate! 
var sharedContext: NSManagedObjectContext! 

@IBOutlet weak var mapView: MKMapView! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
    sharedContext = appDelegate.managedObjectContext 

    mapView.delegate = self 
    self.mapView.addAnnotations(fetchAllPins()) 
} 

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

func fetchAllPins() -> [Shops]? { 
    do { 
     let fetchRequest = NSFetchRequest (entityName: "Shops") 
     let results = try sharedContext.executeFetchRequest(fetchRequest) as! [Shops] 
     return results 

} catch let error as NSError { 
    print("Could not fetch \(error), \(error.userInfo)") 
    } 
} 

回答

1

addAnnotations(:)方法需要一个参数,它是MKAnnotation阵列。你通过它......没有什么,因为allPins没有返回值。您需要更改allPins(),以便它返回一个MKAnnotation的数组。

要使allPins()做到这一点,您需要为每个经纬度对构造一个MKAnnotation,将其添加到数组中,并在该函数的末尾返回该数组。 MKAnnotation是一个协议,所以你不能直接实例化它。你需要有一些采用MKAnnotation的类,创建实例并将这些实例添加到数组中。

+0

我使用返回编辑了代码,但显示错误:无法转换类型'[商店]的值?'到预期的参数类型'[MKAnnotation]' – Rufat

+0

'Shops'是否采用'MKAnnotation'协议? –

+0

您还需要正确处理Swift选项 - 您正在返回'[Shops]?',这是可选的,但您无法将选项传递给'addAnnotations(:)'。你应该确保你总是返回一个数组,而不是一个可选的数组。 –