Search code examples
swiftcore-datansmanagedobject

How do I use this fetchRequest() in Swift?


I am new to swift. I am trying to create a core data NSManagedObject class as I used to do in Objective-C.

In Objective-C I would create something like

+ (Countries *)countryWithName:(NSString *)name
 inManagedObjectContext:(NSManagedObjectContext *)context {

  NSFetchRequest *request = [[NSFetchRequest alloc] init];
  request.entity = [NSEntityDescription entityForName:NSStringFromClass([self class])
                               inManagedObjectContext:context];


  NSPredicate *predicate = [NSPredicate predicateWithFormat:
                            @"(country == %@)", name];

  request.predicate = predicate;

  return [[context executeFetchRequest:request error:nil] lastObject];
}

So, at any time I would like to fetch a country by name on core data, I would do

userCountry = [Countries countryWithName:@"United States" inManagedObjectContext:self.managedObjectContext];

But after creating a NSManagedObject class using swift, I see Xcode created this code inside Countries+CoreDataProperties.swift

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

@NSManaged public var number: Int16
@NSManaged public var name: String?
@NSManaged public var shortcut: NSData?

Now I want to create my class countryByName function. The first line there should be

let fetchRequest = NSFetchRequest(entityName: "Countries") 

but fetchRequest() is already created.

how do I use that?

it will not let me use

let request = Countries.fetchRequest()

giving me an error Ambiguous use of fetchRequest)=


Solution

  • You are using two different entities Countries and Atributos in the fetchRequest() declaration. That indeed ambiguous. The entity must be unique.

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

    and you have to use it

    let fetchRequest : NSFetchRequest<Countries> = Countries.fetchRequest()
    

    Note: It's highly recommended to name entities in singular form. Semantically each record represents one Country not one Countries. Only to-many relationships are supposed to be named in plural form.