Snapshotting saves object state

From EOFWiki
Jump to: navigation, search

Code

#import <Foundation/Foundation.h>
#import <EOControl/EOControl.h>
 
 
@interface NSMutableDictionary ( EOEnterpriseObjectAdditions)
@end
 
 
@implementation NSMutableDictionary ( EOEnterpriseObjectAdditions)
 
- (void) updateFromSnapshot:(NSDictionary *) snapshot
{
   [self removeAllObjects];
   [self addEntriesFromDictionary:snapshot];
}
 
 
- (NSDictionary *) snapshot
{
   return( [[self copy] autorelease]);
}
 
@end
 
 
int main (int argc, const char * argv[])
{
   NSAutoreleasePool     *pool;
   EOEditingContext      *context;
   NSMutableDictionary   *obj;
 
   pool = [NSAutoreleasePool new];
 
   context = [[EOEditingContext new] autorelease];
 
   obj = [NSMutableDictionary dictionary];
 
   [context insertObject:obj];
 
   NSLog( @"A) %@", [context currentEventSnapshotForObject:obj]);  
   [obj willChange]; 
   NSLog( @"B) %@", [context currentEventSnapshotForObject:obj]);  
   [obj setObject:@"1"
           forKey:@"club"];
   NSLog( @"C) %@", [context currentEventSnapshotForObject:obj]);  
   [obj willChange]; 
   NSLog( @"D) %@", [context currentEventSnapshotForObject:obj]);  
   [obj setObject:@"2"
           forKey:@"club"];
   NSLog( @"E) %@", [context currentEventSnapshotForObject:obj]);  
   [context processRecentChanges];
 
   NSLog( @"F) %@", [context currentEventSnapshotForObject:obj]);  
   [obj willChange]; 
   NSLog( @"G) %@", [context currentEventSnapshotForObject:obj]);  
   [obj setObject:@"3"
           forKey:@"club"];
   NSLog( @"H) %@", [context currentEventSnapshotForObject:obj]);  
 
   [pool release];
   return( 0);
}

Comment

Two methods have been added to NSMutableDictionary, that are defined by the EOEnterpriseObject protocol: snapshot and updateFromSnapshot:. These methods translate the state of an object back and from an NSDictionary. During the first willChange the EOEditingContext takes a snapshot of the object, to track the state before changes were applied. Multiple edits are coalesced until processRecentChanges is invoked.

So a snapshot of the object is only taken twice in this scenario by the EOEditingContext, although there are three edits.

Output

A) {}
B) {}
C) {}
D) {}
E) {}
F) { club = 2; }
G) { club = 2; }
H) { club = 2; }
Personal tools