Reputation: 2298
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?
Upvotes: 2
Views: 1597
Reputation: 19335
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.
Upvotes: 2
Reputation: 28217
In addition to Jonathan Pepper's answer, this is a fairly common technique used in numerous examples online:
Whenever you create a new cell in your GetCell
method, set the cell's Tag
using
cell.Tag = Environment.TickCount;
This is especially useful if you have a custom cell object. Your cells can then be tracked in your data source class using a dictionary, for example:
Dictionary<int, your_cell_type> cells = ...
If you need to track something cell specific, you can use the Tag
to look it up on your dictionary object.
Upvotes: 2
Reputation: 26495
You could also use a Guid: http://msdn.microsoft.com/en-us/library/system.guid.newguid.aspx
These are the standard, proven to always be unique, ids for .Net. These are available on Windows as well as Mono running anywhere.
I'm assuming the Tag property is an object and you can store it there (but may be an int knowing Apple). If not, you could subclass UITableViewCell to add a property of type Guid.
Upvotes: 1