Question

I'm trying to get a CoreData entity based on her name, to do that a created a method, that accepts a name parameter (NSString), so this is the method:

-(void)pegarCategoryByName:(NSString *)catName {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSLog(@"Category Name: %@", catName);
    NSError *error = nil;

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Categorias" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"categoria == '%@'", catName];
    [fetchRequest setPredicate:predicate];
   // [fetchRequest setFetchLimit:1];

    NSArray *fetchedObjects = [[self managedObjectContext]executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects.count > 0) {

        _categoriaAtual = [fetchedObjects objectAtIndex:0];

    } else {
        NSLog(@"Category not Found");
    }


}

So lets say i call somewhere in my code:

[self pegarCategoryByName:@"Songs"];

When i run i get the NSLog: Category Name Songs, Category not Found and them the App crashes.

The weird part is, if i change the NSPredicate on pegarCategoryName to not use the NSString passed, here's and example:

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"categoria == 'Songs'"];

Everything works just fine.

Was it helpful?

Solution

Do not enclose the %@ placeholder in the predicate format in quotation marks:

[NSPredicate predicateWithFormat:@"categoria == %@", catName];

OTHER TIPS

catName is already a string; you don't need to surround it with quotes, it would be the same as:

categoria == '@"Songs"'

so remove them:

@"categoria == %@"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top