-(void) awakeFromInsert
{
[super awakeFromInsert];
self.createDate = [NSDate date];
self.title = @"";
// 一意キーを設定する
NSManagedObjectContext* managedObjectContext = [CommonFunctions getAppDelegate].managedObjectContext;
NSFetchRequest* request = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription* entity = [NSEntityDescription entityForName:@"Template" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
[request setResultType:NSDictionaryResultType];
NSExpression* keyPathExpression = [NSExpression expressionForKeyPath:@"templateID"];
NSExpression* maxIDExpression = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription* expressionDescription = [[[NSExpressionDescription alloc] init] autorelease];
expressionDescription.name = @"maxID";
expressionDescription.expression = maxIDExpression;
expressionDescription.expressionResultType = NSDecimalAttributeType;
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
NSError* error = nil;
NSArray* objects = [managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
// エラー
NSLog(@"TemplateID get Error");
self.templateID = [NSNumber numberWithInteger:0];
}
else {
NSInteger initID = 0;
if (objects.count > 0) {
NSDecimalNumber* maxID = [[objects objectAtIndex:0] valueForKey:@"maxID"];
NSLog(@"maxID: %@", maxID);
initID = [maxID integerValue] + 1;
}
NSLog(@"new Template ID: %d", initID);
self.templateID = [NSNumber numberWithInteger:initID];
}
}
コメントする