views:

575

answers:

3

Hi all,

I have a window that looks like so: UI

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 declare:

-(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!

+2  A: 

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.

Brad Larson
+1  A: 

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.

Joshua Nozzi
That will definately work, if I can't get the 1,2,3,4,5 working, I'll use this method. I kinda wanted all numbers from 1 to [number of records] to be used, rather than the number to be based on the date, (which would still work)
Michael
Have a look at this for timeIntervalSinceReferenceDate It isn't independent of the time zone. http://www.mikeash.com/?page=pyblog/friday-qa-2009-11-13-dangerous-cocoa-calls.html
Abizern
Doesn't say anything about the time zone, merely that the clock can be changed. The reference date is in GMT, so the offset would seem to be applied downstream of this call (NSCalendar / NSDateComponents / NSTimeZone, etc.).
Joshua Nozzi
More relevant to Mike Ash's post is what I'd mentioned in my answer: "The only weakness, as I alluded earlier, is the clock being adjusted ..."
Joshua Nozzi
+1  A: 

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

Ztranger
I think I might do something like this, thanks!
Michael