I have a window that looks like so:
Everytime a record is added, I want the repair ID to be set to a unique number that hasn't been used in the table yet. e.g. if there is ID numbers 1,2,3, then when I press +, the ID field should be set to '4'. Also, if one of the records in the table is deleted, so that the ID numbers are: 1,2,4, then when I press +, the number in the Record ID should be set to 3.
At the moment, I have a custom ManagedObject class, where I dec开发者_StackOverflow中文版lare:
-(void)awakeFromInsert {
[self setValue:[NSDate date] forKey:@"date"];
}
In order to set the date to today's date.
How would I go about implementing this unique record ID?
Thanks!
For a pure autoincrementing ID (like was asked for in this question), something like what's described in this message may do the job. Unfortunately, that won't provide values that fill in the blanks for deleted items in your list.
For small amount of records, simply loop through them until you find a free ID. Pseudocode here since I don't know your language:
int RepairID=1;
While isUsed(RepairID) {
RepairID=RepairID+1;
}
return RepairID;
For large numer of records you can keep track of a list of deleted ID:s and the highest ID. When adding a record pick the smallest deleted ID, or if no deleted ids left to reuse, use the highest ID+1
I've used the numerical form of the date before (with a quick check to make sure it's actually unique - ie, the clock hasn't been adjusted). +[NSDate timeIntervalSinceReferenceDate] returns an NSTimeInterval (which is a typedef double). This I believe is independent of time zones, "daylight saving", etc.
The only weakness, as I alluded earlier, is the clock being adjusted, but you could always make sure it's unique. If you have more requirements than what you listed, let me know. I have a few myself, and what I believe to be sufficient work-arounds.
If your using an Array Controller in your interface you can use the count method on its arrangedObjects array to create your ID. You can implement by overriding your -(id)newObject method
//implemented in yourArrayController.m
-(id)newObject
{
//call the super method to return an object of the entity for the array controller
NSManagedObject* yourNewObject = [super newObject];
//set the ID the count of the arrangedObjects array
NSNumber* theID = [NSNumber numberWithInteger:[[self arrangedObjects] count]];
[yourNewObject setValue:theID forKey:@"ID"];
//return your new Object
return yourNewObject;
}
精彩评论