How to use an Nsstring to create an Nspredicate?

Asked

Viewed 72 times

0

I am creating a custom search, but I am creating the strings of the predicate as a Nsstring. However I am getting an error.

Code used:

NSMutableString* escolhasSIM = [[NSMutableString alloc]init];

// Posição 0
    if ([[arrayEscolhas objectAtIndex:0] isEqualToString:@"sim"]) {

         [escolhasSIM appendFormat:@"pizza==sim AND "];
    }


    // Posição 1
    if ([[arrayEscolhas objectAtIndex:1] isEqualToString:@"sim"]) {

        [escolhasSIM appendFormat:@"refrigerante==sim AND "];
    }

// Remove os 5 últimos caracteres para limpar a string
NSString *escolhasSimLimpo = [escolhasSIM substringToIndex:[escolhasSIM length]-5];

// ficando @"pizza==sim AND refrigerante==sim"

// Criando NSPredicate

NSPredicate* argumentosBusca = [NSPredicate predicateWithFormat: escolhasSimLimpo];

But I’m getting the following error:

*** Terminating app due to uncaught Exception 'Nsinvalidargumentexception', Unable to generate SQL for predicate (pizza == yes) (problem on RHS)'

  • 1

    sim is a string, so it needs to be inside of apostrophes, like "refrigerante == 'sim'". A tip, use it array (then do Join) instead of NSMutableString and after having to remove characters, your code gets cleaner.

  • Thanks @Paulorodrigues I will review the code yes, it is because I am just working out a quick solution, then I will refine it.

  • I would recommend using NSCompoundPredicate in place of NSMutableString. In my opinion it would make the code cleaner and more meaningful.

1 answer

0


I made the mistake of including the PROPERTY next to YES.

In fact one should put the argument that will be compared between quotation marks, getting the code like this:

NSMutableString* escolhasSIM = [[NSMutableString alloc]init];

// Posição 0
    if ([[arrayEscolhas objectAtIndex:0] isEqualToString:@"sim"]) {

          // Modo ERRADO
          //[escolhasSIM appendFormat:@"pizza==sim AND "];

            // Modo CORRETO
            [escolhasSIM appendFormat:@"pizza==\"sim\" AND "];
    }


    // Posição 1
    if ([[arrayEscolhas objectAtIndex:1] isEqualToString:@"sim"]) {

        // Modo ERRADO
        //[escolhasSIM appendFormat:@"refrigerante==sim AND "];

        // Modo CORRETO
          [escolhasSIM appendFormat:@"refrigerante==\"sim\" AND "];
    }

// Remove os 5 últimos caracteres para limpar a string
NSString *escolhasSimLimpo = [escolhasSIM substringToIndex:[escolhasSIM length]-5];

// ficando @"pizza==sim AND refrigerante==sim"

// Criando NSPredicate

NSPredicate* argumentosBusca = [NSPredicate predicateWithFormat: escolhasSimLimpo];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.