Isuru
Isuru

Reputation: 31283

Core Data alternative

I'm hitting a few snags when using Core Data to define my model.

1. Can't create objects on-the-fly.

I want to be able to create an object like below and go on adding values to its properties.

let action = Action()
action.desc = "hello"

But if you're using Core Data model classes, you can't do this because you'd get the error Failed to call designated initializer on NSManagedObject class. You have to create a new objects using initWithEntity:insertIntoManagedObjectContext: and all.

2. Can't use the class type as a return type in functions.

When using Core Data, I keep a separate file to put all the fetching/saving methods. In it, I have a method which used to retrieve all the Action objects as an array.

public func loadActions() -> [Action] {
    let fetchRequest = NSFetchRequest()
    let entityDescription = NSEntityDescription.entityForName("Action", inManagedObjectContext: managedObjectContext!)
    fetchRequest.entity = entityDescription

    var error: NSError?
    let result = managedObjectContext?.executeFetchRequest(fetchRequest, error: &error)

    return result!
}

I can't use the type Action to create a typed array because I'd get the error Method cannot be declared public because its result uses an internal type. So I have to get the array as an array of AnyObjects and then cast them to Action whenever I have to use them.

3. Can't have methods within the class.

I know you could create categories back in Objective-C and put all the methods in it. I guess the equivalent in Swift is extensions(?). But it'd be nice if you could have the class and its methods altogether in the same place.

Say I take the OO road and create my entire model the normal way and this brings to my question. How and where can I save these objects?

Upvotes: 2

Views: 1151

Answers (1)

deanWombourne
deanWombourne

Reputation: 38475

This isn't really an answer, but I don't think points 2 and 3 are valid?

  1. Don't make your method public - the issue here isn't anything to do with core data, it's to do with Swift's access levels. You can't make a public method loadActions that returns an internal type Action. You have to either make Action public, or make the method internal (i.e. delete the word public)

  2. You can have the methods in the class - just write them in there? And even if you need to use an extension, you can still put it in the same file?

PS If you do find a good Swift alternative, please let me know. I'm looking for one at the moment - thats how I found your question in the first place!

Upvotes: 1

Related Questions