In Swift, a class does not need to be based on NSObject, unlike ObjC. However, in order to make Swift class accessible to ObjC codes, a Swift class has to be based on NSObject
. I found that if not, I would not see my swift class in [PrjectName]-Swift.h
hidden header file. As a result, you would get compile time error about your class name is unknown identity.
NSObject as a Base Class for Swift Class
During the conversion process, I have to make my Swift class based on
NSObject
. This is quite easy to do.- @objc
- class MyClass: NSManagedObject {
- ...
- }
After all my ObjC classed converted to Swift, none of Swift classes is referenced by ObjC codes, I think I have to remove the base
NSObject
inheritance.CoreData NSManagedObject
Xcode provides interface to generate Swift codes for managed object classes. For example, MyItem entity in Xcode data model, the ObjC files are:
MyItem.h
MyItem.m
corresponding Swift files are:
MyItem+CoreDataProperties.swift
MyItem.swift
For the current Xcode version 7.2 and Swift 2.0, I found that there is one thing missing when you convert ObjC entity class with one to many relations to Swift. For examsle, the following ObjC codes are generated by Xcode long time ago (new Xcode 7.3 generated codes are different but similar):
- #import <Foundation/Foundation.h>
- #import <CoreData/CoreData.h>
- #import "MyItems.h"
- @interface MyEntity : NSManagedObject
- @property (nonatomic, retain) NSString * name;
- @property (nonatomic, retain) NSSet *myItems;
- @end
- @interface MyEntity (CoreDataGeneratedAccessors)
- - (void)addMyItemsObject:(MyItem *)value;
- - (void)removeMyItemsObject:(MyItem *)value;
- - (void)addMyItems:(NSSet *)values;
- - (void)removeMyItems:(NSSet *)values;
- @end
However, the auto-generated Swift codes in (Swift file, for example,
MyItem+CoreDataProperties.swift
) do not contain the corresponding methods.- import Foundation
- import CoreData
- extension MyItem {
- @NSManaged var name: String?
- @NSManaged var myItems: NSSet?
- }
After searching from Internet, I found a solution to manually add those Swift codes. In stead of adding codes to the auto-generated codes, I think that it is better to create a new extension Swift file and to add the missing codes there.
- import Foundation
- extension MyItemItem {
- // The current Xcode does not add the following methods
- // This is what I manually added
- @NSManaged func addMyItemsObject(value:MyItem)
- @NSManaged func removeMyItemsObject(value:MyItem)
- @NSManaged func addMyItems(value:Set<MyItem>)
- @NSManaged func removeMyItems(value:Set<MyItem>)
- }
References
- StackOverFlow QA: Setting an NSManagedObject relation in Swift
- Apple Developer Site: Migration Your Objective-C Code to Swift