mvasco
mvasco

Reputation: 5101

Number of core data objects with a defined attribute value

I am using following fetch request to delete core data objects:

NSEntityDescription *entity=[NSEntityDescription entityForName:@"entityName" inManagedObjectContext:context];
  NSFetchRequest *fetch=[[NSFetchRequest alloc] init];
  [fetch setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(value1 == %@) AND (value2 == %@)", data1, data2];
 [fetch setPredicate:predicate];
  //... add sorts if you want them
  NSError *fetchError;
  NSArray *fetchedData=[self.moc executeFetchRequest:fetch error:&fetchError];
 for (NSManagedObject *product in fetchedProducts) {
    [context deleteObject:product];
  }

What I need is to execute the fetch request only if the number of objects in the core data entity with [value1 isEqualToString: @"borrar"] is greater than 1. How could I add this condition?

***EDIT The attribute value1 is a transient attribute.

Upvotes: 0

Views: 657

Answers (2)

Martin R
Martin R

Reputation: 539815

To check how many objects with a given attribute value exist, use countForFetchRequest::

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"entityName"];
[request setPredicate:[NSPredicate predicateWithFormat:@"value1 = %@", @"borrar"]];
NSError *error;
NSUInteger count = [self.moc countForFetchRequest:request error:&error];
if (count == NSNotFound) {
    // some error occurred
} else if (count > 1) {
    // more the one object with "value1 == borrar"
} 

Update (according to the edited question): You cannot use a transient attribute in a Core Data fetch request. If "value1" is a transient attribute, you can only fetch all objects with "value2 == something", and then iterate over the fetched array to check if there is more than one object with "value1 == borrar".

Upvotes: 1

Prad
Prad

Reputation: 51

NSPredicate *predicate=[NSPredicate predicateWithFormat:@"(Value1 == borrar)"];
[fetch setPredicate:predicate];
NSError *fetchError;
NSArray *fetchedData=[self.moc executeFetchRequest:fetch error:&fetchError];
for(int i=0;i<fechedData.count;i++){
     [context deleteObject:[fechedData objectAtIndex:i]valueForKey:@"Value1"];
}

Upvotes: 1

Related Questions