Reputation: 1979
I'm having trouble getting my NSManagedObject to work.
In one file I have:
import UIKit
import CoreData
@objc(Location)
class Location: NSManagedObject {
@NSManaged var title:String
@NSManaged var lat:NSDecimalNumber
@NSManaged var lon:NSDecimalNumber
@NSManaged var course:NSDecimalNumber
@NSManaged var alt:NSDecimalNumber
}
In a TableView class I have:
...
var locations:NSArray = [Location]()
override func viewDidLoad() {
super.viewDidLoad()
locations = self.getAllLocations()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var logCell:TableViewCell = self.tableView.dequeueReusableCellWithIdentifier("loggedCell") as TableViewCell
logCell.loggedTitle.text = locations[indexPath.row].title
if let lat = locations[indexPath.row].lat {
println(lat)
}
return logCell
}
func getAllLocations() -> [Location] {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Locations")
request.returnsObjectsAsFaults = false
if let results = context.executeFetchRequest(request, error: nil) {
return results as [Location]
} else {
// Failed, return empty error. Alternatively, report error.
return []
}
}
...
I am able to retrieve the values from CoreData. If I println( locations[indexPath.row] ) it's all there. However in func tableView I am only able to get the title. lat, lon, everything but title errors out with 'AnyObject' does not have a member named 'lat', as in the lines:
if let lat = locations[indexPath.row].lat {
println(lat)
}
I'm sure it's something basic as I am new to Swift and iOS development. I would appreciate a point in the right direction please.
Upvotes: 0
Views: 175
Reputation: 535229
It's partly about Swift's strict typing and partly about the interplay between Swift types and Cocoa (Objective-C) types.
The problem here is that you have typed locations
as an NSArray. That's a Cocoa collection, not a Swift collection. Swift doesn't know what kind of thing is inside an NSArray.
You may know (or believe) that what's at locations[indexPath.row]
is a Location, therefore, but Swift doesn't know that. You have to tell it, by casting (with as
).
Alternatively, if there is no reason not to do so, type locations
as a Swift array of Location, a [Location]
. Now Swift knows what's in it. I should also point out that as things stand, your initializer is pointless:
var locations:NSArray = [Location]()
You start by making a Swift array of Location, yes, but then by typing locations
as an NSArray and assigning into it, you throw away all knowledge that this thing is supposed to contain only Location objects.
Upvotes: 1