Ok, just starting to look at Swift and trying to use a Coredata model and SQLfile from an existing Obj-C program.
- Created new swift Coredata project
- replaced the coredata model with the existing model
- pointed program to sql data file
- Created Swift
NSMangagedObjectSubclass
Run program, get an error that class types don't match.
- Remove Swift
NSMangedObjectSubclass and created Objective-C version
Run program, no issues, fetch executes nicely.
I want to eventually rewrite the program in swift, but I'll have to deal with old SQL data files. Is there a way to get this to work without having to blend the two languages?
I have not tried this, but is this something lightweight migration would do?
-[EDIT]---
Error message is in console:
"fatal error: NSAarry element failed to match the Swift Array Element type"
fetch Code:
let request = NSFetchRequest(entityName: "Account")
var error:NSError?=nil
var fetchResults = managedObjectContext?executeFetchRequest(request, error: &error)! as [Account]
for aAccount in fetchResults {
println(aAccount.name)
}
This code does works - IF the NSManagedObject Subclass (Account) IS Obj-C
This code does NOT work - IF the NSManagedObject subclass (Account) IS Swift - This is when I get the error.
The NSManagedObject Subclass is generated through "Create NSMangedObject Subclass" in XCode.
The CoreData Model and the SQL data file are from a previous, functioning, program when 100% Obj-C.
-[EDIT 2]-------
Unless I did something wrong, it is type cased...
var fetchResults = ...(request, error: &error)! as [Account]
To test, I changed the above to:
var fetchResults = ...(request, error: &error)! as [NSManagedObject]
with this change the following works - as you would expect:
for aAccount in fetchResults {
println(aAccount.valueForKey("name")!)
}
The following DOES NOT work (added it inside the for-in loop):
if let account = aAccount as? Account {
println(account.name)
}
So, it will NOT let me cast to the Swift Account Class. I used Xcode's "Create ManagedObject Subclass" to create the Swift subclass.
-[EDIT 3]-----
XCode Version: 6.1
Account.swift file:
import Foundation
import Coredata
class Account: NSManagedObject {
@NSManaged var name: String
@NSManaged var number: String
@NSManaged var type: String
@NSManaged var status: String
}
If I create an Obj-C version of Account (Account.h and Account.m), add them to the Bridging-Header, remove the .swift version, everything works.
Accoutbut your entity name isAccount(note the missing 'n') - David Berry