开发者

NSPredicate syntax to exclude a given NSManagedObject

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 fet开发者_运维百科chMyManagedObjectsWithPredicateOrNil: 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?


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];
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜