Encapsulate Core Data Object's data? - swift

Is it a good practice to encapsulate a Core Data Model's data? just like you would in any other class, and implement getters and setters to retrieve and set data to it?
For example:
public class MyModel: NSManaged {
var name: String {
get { self._name }
set { self._name = newValue }
}
}
extension MyModel {
#nonobjc public class func fetchRequest() -> NSFetchRequest<MyModel> {
return NSFetchRequest<MyModel>(entityName: "MyModel")
}
#NSManaged fileprivate var _name: String
}

Related

How to map model for NSManagedObject?

When I try to do this, the model is stored in the NSManagedObjectContext if I use the context, and without it it throws an error, but I'm not expecting the same result.
Is there an easy way to implement this?
class WordDal: NSManagedObject {
#nonobjc public class func fetchRequest() -> NSFetchRequest<WordDal> {
return NSFetchRequest<WordDal>(entityName: "WordDal")
}
#NSManaged public var word: String?
#NSManaged public var uuid: UUID?
}
struct WordPresentation {
let word: String
let uuid: UUID
}
func mappingNSManagedObject(_ wordPresentation: WordPresentation) -> WordDal {
let model = WordDal()
model.uuid = wordPresentation.uuid
model.word = wordPresentation.word
return model
}
Consider to redesign your model to have computed property for the new wrapper type that transforms the property value to and from the wrapper value.
Implementing a computed property in a Swift Core Data model is often a clear, more intuitive way to achieve what you need.
Here is an example implementation:
struct WordPresentation {
let word: String
let uuid: UUID }
class WordDal: NSManagedObject {
#nonobjc public class func fetchRequest() -> NSFetchRequest<WordDal> {
return NSFetchRequest<WordDal>(entityName: "WordDal")
}
#NSManaged public var word: String?
#NSManaged public var uuid: UUID?
var wordPresentation : WordPresentation {
get {
return WordPresentation(word: self.word, uuid: self.uuid)
}
set {
self.word = newValue.name
self.uuid = newValue.id
}
}
}
I solved the problem like this (I don't know why I put it off and didn't understand right away):
class WordDal: NSManagedObject {
#nonobjc public class func fetchRequest() -> NSFetchRequest<WordDal> {
return NSFetchRequest<WordDal>(entityName: "WordDal")
}
#NSManaged public var word: String?
#NSManaged public var uuid: UUID?
}
struct WordPresentation {
let word: String
let uuid: UUID
}
func removeFromStorage(by uuid: UUID) {
getDataFromStorage { [weak self] objects in
guard let self = self else { return }
if let objectForRemove = objects.first(where: { $0.uuid == uuid }) {
self.coreDataStack.mainContext.delete(objectForRemove)
self.coreDataStack.saveContext(self.managedObjectContext)
}
}
}
I'm creating a presentation level model with UUID!
And I delete only on him himself UUID.
Now I can walk both ways.

Can't store custom data in child NSManagedObject with Xcode 10.2.1

I updated Xcode to 10.2.1 and noticed that I can't init and store any custom properties in child NSManagedObject class (It worked in previous Xcode version). Is anybody has the same problem?
I created new project. If I'll create ONE parent and ONE child entity. I able to store custom data ONLY in parent entity but if I'll store some custom class in child one, the property will be always nil.
Here is parent entity:
#objc(Entity)
public class Entity: NSManagedObject {
class var entityName: String {
return String(describing: self)
}
private var testClass = MyTestClass()
init() {
let entityName: String = type(of: self).entityName
let context: NSManagedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
guard let entityDescription: NSEntityDescription = NSEntityDescription.entity(forEntityName: entityName, in: context) else {
fatalError("Failed to create entity description for name: \(entityName)")
}
super.init(entity: entityDescription, insertInto: context)
print(testClass.testProperty)
}
}
extension Entity {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Entity> {
return NSFetchRequest<Entity>(entityName: "Entity")
}
#NSManaged public var title: String?
}
Here is child entity:
#objc(EntityChild)
public class EntityChild: Entity {
private var testClassChild = MyTestClass()
override init() {
super.init()
print(testClassChild.testProperty)//on this line app will crash
}
}
extension EntityChild {
#nonobjc public class func fetchRequest() -> NSFetchRequest<EntityChild> {
return NSFetchRequest<EntityChild>(entityName: "EntityChild")
}
#NSManaged public var title2: String?
}
Also attaching screenshots of code execution:
Note
it works as expected if use property as lazy or if add properties as force unwrapped and initialize them in init

Function accepting generic parameters

I have a subclass of NSManagedObject. I'm using a protocol to create a "wrapper" class. In my controller the data can be either: Items or Item1. To be able to use my function I'll have to add the protocol ItemInfo to Items but that means I'll have to add
var items: Items { return self }
in Items, which seems a bit redundant. I've tried creating a base class but that didn't work.
Question:
Is there a better way to let my function accept both Items and Item1 as parameter like using generics?
NSManagedObject:
class Items: NSManagedObject {
#NSManaged var name: String
#NSManaged var code: String
}
Protocol:
protocol ItemInfo {
var item: Items { get }
}
extension ItemInfo {
var name : String { return item.name }
var code : String { return item.code }
}
Wrapper:
class Item1: ItemInfo {
let item: Items
init(item: Items) { self.item = item }
}
function:
func handleItem(item: ItemInfo) {
print(item.name)
print(item.code)
}
I could use:
func handleItem<T>(item: T) {
if let a = item as? Items {
print(a.name)
print(a.code)
}
if let a = item as? ItemInfo {
print(a.name)
print(a.code)
}
}
But this doesn't seem the right way ...
If I understand correctly what you are trying to achieve (function accepting two kind of items), I would use protocol as type accepted by function, refer the code below
class Items: NSManagedObject, ItemInfo {
#NSManaged var name: String
#NSManaged var code: String
}
class Item1: NSManagedObject, ItemInfo {
#NSManaged var name: String
#NSManaged var code: String
}
protocol ItemInfo {
var name: String {get set}
var code: String {get set}
}
and function would look like this
func handle(item: ItemInfo) {
print(item.code)
print(item.name)
}

Swift override generic swift

I am trying to implement generic for MVVM Swift. I have two base class, an protocol for generic class. The special in here is inheritance. I tried for three hour but I can't fix it :(.
protocol ObjectProtocol {
var id: Int { get set }
var name: String { get set }
}
class BaseViewModel<T: ObjectProtocol> {
var objects: [T] = []
init(){
}
}
protocol ListViewControllerType {
associatedtype T: ObjectProtocol
associatedtype ViewModelType: BaseViewModel<T>
var viewModel: ViewModelType! { get set }
func showError(error: String)
}
extension ListViewControllerType {
func showError(error: String) {
print(error)
}
}
class Consult: ObjectProtocol {
var id: Int = 1
var name: String = "Consult"
}
class ConsultViewModel<T: Consult>: BaseViewModel<Consult> {
}
class ConsultViewController: ListViewControllerType {
var viewModel: ConsultViewModel<Consult>!
}
But I get error in var viewModel: ConsultViewModel<Consult>!
This is error: Type 'ConsultViewController' does not conform to protocol 'ListViewControllerType'
Someone have experience with generic and inheritance can help me please.
Thank you so much.
I usually do like this:
class BaseViewModel {
}
class TemplateViewModel<T: ObjectProtocol>: BaseViewModel {
var objects: [T] = []
init(){
}
}

Can you create a Swift base class that requires its subclasses to implement method(s)? [duplicate]

Is there a way to create an abstract class in the Swift Language, or is this a limitation just like Objective-C? I'd like to create a abstract class comparable to what Java defines as an abstract class.
There are no abstract classes in Swift (just like Objective-C). Your best bet is going to be to use a Protocol, which is like a Java Interface.
With Swift 2.0, you can then add method implementations and calculated property implementations using protocol extensions. Your only restrictions are that you can't provide member variables or constants and there is no dynamic dispatch.
An example of this technique would be:
protocol Employee {
var annualSalary: Int {get}
}
extension Employee {
var biweeklySalary: Int {
return self.annualSalary / 26
}
func logSalary() {
print("$\(self.annualSalary) per year or $\(self.biweeklySalary) biweekly")
}
}
struct SoftwareEngineer: Employee {
var annualSalary: Int
func logSalary() {
print("overridden")
}
}
let sarah = SoftwareEngineer(annualSalary: 100000)
sarah.logSalary() // prints: overridden
(sarah as Employee).logSalary() // prints: $100000 per year or $3846 biweekly
Notice that this is providing "abstract class" like features even for structs, but classes can also implement the same protocol.
Also notice that every class or struct that implements the Employee protocol will have to declare the annualSalary property again.
Most importantly, notice that there is no dynamic dispatch. When logSalary is called on the instance that is stored as a SoftwareEngineer it calls the overridden version of the method. When logSalary is called on the instance after it has been cast to an Employee, it calls the original implementation (it doesn't not dynamically dispatch to the overridden version even though the instance is actually a Software Engineer.
For more information, check great WWDC video about that feature: Building Better Apps with Value Types in Swift
Note that this answer is targeted at Swift 2.0 and above
You can achieve the same behaviour with protocols and protocol extensions.
First, you write a protocol that acts as an interface for all the methods that have to be implemented in all types that conform to it.
protocol Drivable {
var speed: Float { get set }
}
Then you can add default behaviour to all types that conform to it
extension Drivable {
func accelerate(by: Float) {
speed += by
}
}
You can now create new types by implementing Drivable.
struct Car: Drivable {
var speed: Float = 0.0
init() {}
}
let c = Car()
c.accelerate(10)
So basically you get:
Compile time checks that guarantee that all Drivables implement speed
You can implement default-behaviour for all types that conform to Drivable (accelerate)
Drivable is guaranteed not to be instantiated since it's just a protocol
This model actually behaves much more like traits, meaning you can conform to multiple protocols and take on default implementations of any of them, whereas with an abstract superclass you're limited to a simple class hierarchy.
I think this is the closest to Java's abstract or C#'s abstract:
class AbstractClass {
private init() {
}
}
Note that, in order for the private modifiers to work, you must define this class in a separate Swift file.
EDIT: Still, this code doesn't allow to declare an abstract method and thus force its implementation.
The simplest way is to use a call to fatalError("Not Implemented") into the abstract method (not variable) on the protocol extension.
protocol MyInterface {
func myMethod() -> String
}
extension MyInterface {
func myMethod() -> String {
fatalError("Not Implemented")
}
}
class MyConcreteClass: MyInterface {
func myMethod() -> String {
return "The output"
}
}
MyConcreteClass().myMethod()
After I struggled for several weeks, I finally realized how to translate a Java/PHP abstract class to Swift:
public class AbstractClass: NSObject {
internal override init(){}
public func getFoodToEat()->String
{
if(self._iAmHungry())
{
return self._myFavoriteFood();
}else{
return "";
}
}
private func _myFavoriteFood()->String
{
return "Sandwich";
}
internal func _iAmHungry()->Bool
{
fatalError(__FUNCTION__ + "Must be overridden");
return false;
}
}
public class ConcreteClass: AbstractClass, IConcreteClass {
private var _hungry: Bool = false;
public override init() {
super.init();
}
public func starve()->Void
{
self._hungry = true;
}
public override func _iAmHungry()->Bool
{
return self._hungry;
}
}
public protocol IConcreteClass
{
func _iAmHungry()->Bool;
}
class ConcreteClassTest: XCTestCase {
func testExample() {
var concreteClass: ConcreteClass = ConcreteClass();
XCTAssertEqual("", concreteClass.getFoodToEat());
concreteClass.starve();
XCTAssertEqual("Sandwich", concreteClass.getFoodToEat());
}
}
However I think Apple did not implement abstract classes because it generally uses the delegate+protocol pattern instead. For example the same pattern above would be better done like this:
import UIKit
public class GoldenSpoonChild
{
private var delegate: IStomach!;
internal init(){}
internal func setup(delegate: IStomach)
{
self.delegate = delegate;
}
public func getFoodToEat()->String
{
if(self.delegate.iAmHungry())
{
return self._myFavoriteFood();
}else{
return "";
}
}
private func _myFavoriteFood()->String
{
return "Sandwich";
}
}
public class Mother: GoldenSpoonChild, IStomach
{
private var _hungry: Bool = false;
public override init()
{
super.init();
super.setup(self);
}
public func makeFamilyHungry()->Void
{
self._hungry = true;
}
public func iAmHungry()->Bool
{
return self._hungry;
}
}
protocol IStomach
{
func iAmHungry()->Bool;
}
class DelegateTest: XCTestCase {
func testGetFood() {
var concreteClass: Mother = Mother();
XCTAssertEqual("", concreteClass.getFoodToEat());
concreteClass.makeFamilyHungry();
XCTAssertEqual("Sandwich", concreteClass.getFoodToEat());
}
}
I needed this kind of pattern because I wanted to commonize some methods in UITableViewController such as viewWillAppear etc. Was this helpful?
There is a way for simulating abstract classes using Protocols.
This is an example:
protocol MyProtocol {
func doIt()
}
class BaseClass {
weak var myDelegate: MyProtocol?
init() {
...
}
func myFunc() {
...
self.myDelegate?.doIt()
...
}
}
class ChildClass: BaseClass, MyProtocol {
override init(){
super.init()
self.myDelegate = self
}
func doIt() {
// Custom implementation
}
}
One more way how you can implement abstract class is to block initializer.
I've done it this way:
class Element:CALayer { // IT'S ABSTRACT CLASS
override init(){
super.init()
if self.dynamicType === Element.self {
fatalError("Element is abstract class, do not try to create instance of this class")
}
}
}
It's a really old question but still… Here's a snippet of actual code that compiles on Swift 5.2 and works as intended:
protocol Context {
init() throws
func out(_ aStr: String) throws
// Other stuff
}
class AbstractContext: Context {
required init() throws {
if Self.self === AbstractContext.self {
preconditionFailure("Call to abstract method \(Self.self).\(#function)")
}
}
func out(_ aStr: String) throws {
preconditionFailure("Call to abstract method \(Self.self).\(#function)")
}
// Other stuff
}
class CompileContext: AbstractContext {
required init() throws {}
override func out(_ aStr: String) throws {
print(aStr)
}
// Other stuff
}
And here's what I get once I remove CompileContext.out:
Fatal error: Call to abstract method CompileContext.out(_:): file swiftpg/contexts.swift, line 28
With the limitation of no dynamic dispatch, you could do something like this:
import Foundation
protocol foo {
static var instance: foo? { get }
func prt()
}
extension foo {
func prt() {
if Thread.callStackSymbols.count > 30 {
print("super")
} else {
Self.instance?.prt()
}
}
}
class foo1 : foo {
static var instance : foo? = nil
init() {
foo1.instance = self
}
func prt() {
print("foo1")
}
}
class foo2 : foo {
static var instance : foo? = nil
init() {
foo2.instance = self
}
func prt() {
print("foo2")
}
}
class foo3 : foo {
static var instance : foo? = nil
init() {
foo3.instance = self
}
}
var f1 : foo = foo1()
f1.prt()
var f2 : foo = foo2()
f2.prt()
var f3 : foo = foo3()
f3.prt()
I was trying to make a Weather abstract class, but using protocols wasn't ideal since I had to write the same init methods over and over again. Extending the protocol and writing an init method had it's issues, especially since I was using NSObject conforming to NSCoding.
So I came up with this for the NSCoding conformance:
required init?(coder aDecoder: NSCoder) {
guard type(of: self) != Weather.self else {
fatalError("<Weather> This is an abstract class. Use a subclass of `Weather`.")
}
// Initialize...
}
As for init:
fileprivate init(param: Any...) {
// Initialize
}
Move all references to abstract properties and methods of Base class to protocol extension implementation, where Self constraint to Base class. You will gain access to all methods and properties of Base class. Additionally compiler check implementation of abstract methods and properties in protocol for derived classes
protocol Commom:class{
var tableView:UITableView {get};
func update();
}
class Base{
var total:Int = 0;
}
extension Common where Self:Base{
func update(){
total += 1;
tableView.reloadData();
}
}
class Derived:Base,Common{
var tableView:UITableView{
return owner.tableView;
}
}