Search code examples
uitableviewxamarin.iosdeque

UITableViewCell unique identifier?


I'm looking for a way to uniquely identify instances of UITableViewCells even after they have been recycled (dequeued) via DequeueReusableCell(string identifier) - without subclassing or using a container object.

So basically, when I create a new cell, I want to use a unique id of this cell as a key to store another related object in a dictionary. Later on, when the cell get's recycled/dequeued, I want to read the related objected from the dictionary. I am totally aware that the recycled cell may be placed at any index path in the table and may (most likely) contain other data than before - the other object really is related to the cell instance, not the index path.

Loosing relation to the object must be avoided. The obtained id must at all cost be the same that was used when the cell was created.

This was previously achieved by generating a random number and storing it as the cell's tag. However, those tags could collide (when the same random number is generated twice) and I would only want to implement collision avoidance as a last resort. So I'm looking for a better way.

I've looked at ClassHandle, Handle and SuperHandle properties. The only one staying consistent among dequeues seems to be the ClassHandle.

Is it safe to use the ClassHandle property for this purpose? If not, what other options are there?


Solution

  • You can create your own monotonically increasing number:

    static int monotonicNumber;
    

    and then set the tag to:

    cell.Tag = System.Threading.Interlocked.Increment (ref monotonicNumber);
    

    Note that Environment.TickCount isn't guaranteed to be unique, you can get identical tick counts if you fetch it in rapid succession. I know because it has happened to me.