The second method you are looking for is not appropriate to add to the entity itself. It needs to be somewhere above the entities, most likely in your controller object.
The first method is as follows:
- (void)updateDate:(NSDate*)date andValue:(NSInteger)value
{
[self setValue:date forKey:@"date"];
[self setValue:[NSNumber numberWithInteger:value] forKey:@"value"];
}
This is fairly straight KVC (Key-Value Coding) and I highly recommend that you read Apple's docs on the subject.
For your other method, that should be in a controller, you need to perform a fetch to find the record.
- (id)findRecordForDate:(NSDate*)date inManagedObjectContext:(NSManagedObjectContext*)moc
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:moc]];
[request setPredicate:[NSPredicate predicateWithFormat:@"date == %@", date]];
NSError *error = nil;
NSArray *objects = [moc executeFetchRequest:request error:&error];
NSAssert1(error == nil, @"Error fetching object: %@", [error localizedDescription]);
return [objects lastObject];
}
- (void)incrementEntityWithDate:(NSDate*)date
{
id entity = [self findRecordForDate:date inManagedObjectContext:[self managedObjectContext]];
NSInteger value = [[entity valueForKey:@"value"] integerValue];
value += 1;
[entity setValue:[NSNumber numberWithInteger:value] forKey:@"value"];
}
This is also very straightforward Core Data access. I recommend you read up on how Core Data works.
As an aside, using a date as a unique is a very bad design.
UPDATE
Marcus, Thanks for the answer. It is really helpful. I am new to core data so I have a few questions to make things clearer.
The code for the first method sets two values, but it doesn't insert the new record into the table. How can I insert the newly created record into the table?
You need to read up on how Core Data works. Apple has great documentation on how Core Data works and if that fails you can buy my book. There is a TON of information about how to use Core Data on the internet.
Where should I put the first method? in my .m file?
This is basic Objective-C. If you are asking this question you need to step way back and learn the fundamentals of the language first.
You mentioned that I need to add the second method in the controller. But the controller is defined in the xib file. How can I add the second method to that?
The controller is never defined in the xib file. It is referenced in the xib file. Again, you need to go back to the beginning of how Objective-C works and learn the basics before you dive this deep.