Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing a variable for Element name in Core Data Predicate
    primarykey
    data
    text
    <p>I am trying to write a method which tries to retrieve an object based on a predicate using a variable (as part of a NSXMLParser). The code looks like this:</p> <p>I have these variables defined in the class:</p> <pre><code>@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext; @property (strong, nonatomic) NSString *model; @property (strong, nonatomic) NSString *element; </code></pre> <p>Now in the method, I set up the request like this:</p> <pre><code>NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:self.model inManagedObjectContext:self.managedObjectContext]; [request setEntity:entity]; </code></pre> <p>Now the challenge - what I <strong>want</strong> to be able to do is:</p> <pre><code>// DOES NOT WORK [request setPredicate:[NSPredicate predicateWithFormat:@"%@ == %@", self.element,string]]; </code></pre> <p>But that does not return any results. After some mucking around, I notice that this <strong>does</strong> work:</p> <pre><code> if ( [self.element isEqualToString:@"name"] ) { [request setPredicate:[NSPredicate predicateWithFormat:@"name == %@", string]]; } </code></pre> <p>This tells me that my <code>self.element</code> is set correctly (I think?) but that the predicate doesn't like the left hand side of the expression being a variable.</p> <p>I also tried:</p> <pre><code>[request setPredicate:[NSPredicate predicateWithFormat:@"%s == %@", [self.element UTF8String],string]]; </code></pre> <p>... just to see if perhaps it preferred a string. I couldn't make that work either.</p> <p>Is what I am attempting even possible? I've read as much as I can of the Core Data documentation and I can't find any sample code which does it this way, but I also didn't find anything to say it wasn't possible.</p> <p>EDIT: and now the working code:</p> <pre><code>[request setPredicate:[NSPredicate predicateWithFormat:@"%K == %@", self.element,string]]; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload