Yaroslav Tytarenko
Yaroslav Tytarenko

Reputation: 33

Core Data: What difference between insertNewObject vs designated initializer

I have found two solutions to the problem:

public class MyClass: NSManagedObject {
    init(_ entity:NSEntityDescription, dict: NSDictionary, context: NSManagedObjectContext) {
        super.init(entity: entity , insertInto: context)
    }
}

let entity = NSEntityDescription.entity(forEntityName: "MyClass", in: self.context!)
_ = MyClass.init(entity!, dict: item as! NSDictionary, context: self.context!)

and

let myClass = NSEntityDescription.insertNewObject(forEntityName: "MyClass", into: context) as! MyClass

but I cannot understand the difference in the end. And how does it affect NSManagedObjectContext?

Upvotes: 3

Views: 1133

Answers (2)

butkovskiym
butkovskiym

Reputation: 33

init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) initializer available for iOS 3.0+

init(context: NSManagedObjectContext) initializer available for iOS 10.0+

I use both initializers to maintain compatibility with iOS < 10.0, there is no difference between them.

Upvotes: 1

Tom Harrington
Tom Harrington

Reputation: 70966

The have the same effect. The method on NSEntityDescription is a "factory" method, which you don't see too often in Objective-C (that method existed before Swift did). But the end result is the same as using the designated initializer. Although the factory method's code is not available, you can assume that it calls the designated initializer at some point.

Upvotes: 3

Related Questions