如何向核心数据模型子类添加方法

时间:2018-11-25 20:33:58

标签: swift core-data

我想向生成的子类实体添加方法或自定义属性。

//---------------- Books+CoreDataClass.swift ----------
import Foundation
import CoreData

@objc(Books)
public class Books: NSManagedObject {

}
//--------------------------end file Books+CoreDataClass.swift —

//----------- Books+CoreDataProperties.swift
//
import Foundation
import CoreData

extension Books {

@nonobjc public class func fetchRequest() -> NSFetchRequest<Event> {
    return NSFetchRequest<Books>(entityName: "Books")
}

@NSManaged public var bookNumber: Int16
@NSManaged public var bookName: String?
@NSManaged public var chapterNumber: Int16
@NSManaged public var chapterName: String?
@NSManaged public var imageNumber: Int16
@NSManaged public var imageName: String?
@NSManaged public var description: String?
@NSManaged public var timestamp: NSDate?
// ---------When I was using Object-c, I used to have the following
//
// - (NSString *)sortingSectionAttribute
// {
// return [NSString stringWithFormat:@“Book: %@ - Chapter: %@”, self.bookNumber, self. chapterNumber ];
// }

}
///-------------------end file Books+CoreDataProperties.swift ------

但是我不知道如何在Swift中做到这一点。尽管我尝试了多种方法来完成此操作,但是当我运行应用程序并点击 让aFetchedResultsController = NSFetchedResultsController(fetchRequest:fetchRequest,managedObjectContext:self.managedObjectContext !, sectionNameKeyPath:“ sortingSectionAttribute”,cacheName:nil)

1 个答案:

答案 0 :(得分:0)

我迅速创建了上述方法,并在方法声明的前面添加了objc,它可以按我的意愿工作。