How to Add a Method to Core Data Model Subclasses

want to add a method or a custom attribute to the generate subclass Entity.

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

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 ------

But I don’t know how to do it in Swift. Though I tried many ways to accomplish this but it gives me an error when I run the app and hit the
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: “sortingSectionAttribute”, cacheName: nil)

Thank you for your Help

Problem solved.
I just added objc infront of the Swift method and it work as I want.

@msuboh Thank you for sharing the solution - much appreciated! :]

This topic was automatically closed after 166 days. New replies are no longer allowed.