2014-06-08 3 views
11

Sto provando a spostare un po 'di codice RubyMotion su Swift. Finora funziona. Quello che non capisco è il motivo per cui il seguente risultato non può essere colato per la classe documento:Perché insertNewObjectForEntityForName restituisce solo NSManagedObject?

var newObject : NSManagedObject 
    NSEntityDescription.insertNewObjectForEntityForName("Document", inManagedObjectContext:context) 
    as NSManagedObject 

La chiamata insertNewObjectForEntityForName restituisce un oggetto di tipo NSManagedObject. Ma perché non inserire NewObjectForEntityForName restituisce un oggetto di tipo Documento come specificato da entity.managedObjectClassName?

mio entità simile a questa:

func DocumentEntity() -> NSEntityDescription { 

    var entity = NSEntityDescription() 
    entity.name = "Document" 
    entity.managedObjectClassName = "Document" 

    var property = NSAttributeDescription() 
    property.name = "title" 
    property.attributeType = NSAttributeType.StringAttributeType 
    property.optional = false 

    entity.properties = [property] 

    return entity 
} 

class Document : NSManagedObject { 
    @NSManaged var title : String 
} 

model = NSManagedObjectModel() 
model.entities = [DocumentEntity()] 

var store = NSPersistentStoreCoordinator(managedObjectModel: model) 

risposta

0

Hai provato:

var document = NSEntityDescription.insertNewObjectForEntityForName("Document", inManagedObjectContext: context) as? Document 

questo funziona per me.

+0

come? NSManagedObject restituisce l'oggetto ma come? Documento restituito n. – rogergl

+0

stessa cosa mi succede con alcune classi di Core Data. – Jigzat

5

La soluzione è aggiungere il nome del modulo al nome della classe.

ad es.

var entity = NSEntityDescription() 
entity.name = "Document" 
entity.managedObjectClassName = "TestSwift.Document" 
+0

Funziona anche nell'editor di modelli Xcode CoreData, dove "TestSwift" è il nome del progetto. –

+0

Il modo corretto di gestirlo è nella mia risposta. http://stackoverflow.com/a/24786866/1281407 – mprivat

17

È necessario aggiungere @objc(Document) alla classe documento. Questo è così che i Core Data (che sono ancora in Objective-C) possono gestire la tua classe Swift.

@objc(Document) 
class Document : NSManagedObject { 
    @NSManaged var title : String 
} 

Poi sarà tutto il lavoro:

var document = NSEntityDescription.insertNewObjectForEntityForName("Document", inManagedObjectContext: context) as Document 

restituirà il giusto tipo

+1

Questo mi ha infastidito per un po 'ma questo ha risolto il mio problema. Grazie! – mikeytdan

+0

Funziona, ma mi chiedo se è davvero il modo giusto, o se @ rogergl è corretto. –

3

Assicurarsi di impostare il nome della classe di voi entità nel modello a oggetti. Il formato è YourAppModule.YourClassName.

enter image description here