views:

116

answers:

1

Hello all. I have a Core Data store in which many of the entities should be unique instances of their particular NSEntityDescription. I'm currently doing this by creating a new entity for a given description, then this:

-(void)clearMyManagedObjectsExceptFor:(NSManagedObject*)except {

    NSArray *managedObjects = [ self fetchMyManagedObjectsWithPredicateOrNil: nil ];
    // returns all managed objects for a given NSEntityDescription

    NSManagedObject *managedObject;
    for( NSUInteger i = 0; i < [ managedObjects count ]; i++ ){
        managedObject = [ managedObjects objectAtIndex: i ];
        if( ![ managedObject isEqual: except ] ){
            [ managedObjectContext deleteObject: managedObject ];
        }
    }
}

Which works, but it feels like I should be able to do that != with an NSPredicate rather than in the iteration, but I just can't figure out the right predicate syntax to do it. Can anyone enlighten me?

+2  A: 

You could do something like this:

- (void) clearObjectsExceptFor:(NSManagedObject *)exception {
  NSPredicate * allExcept = [NSPredicate predicateWithFormat:@"SELF != %@", exception];
  NSArray * objects = [self fetchMyManagedObjectsWithPredicateOrNil:allExcept];
  for (NSManagedObject * object in objects) {
    [managedObjectContext deleteObject:object];
  }
}
Dave DeLong
Y'know, I could swear I'd tried that, but I just did again and it worked *facepalm. Thanks!
Henry Cooke