开发者

Core Data order: Can I use a float?

I've been pondering how best to order a set of Core Data managed objects, and I wanted to throw out an idea I haven't seen used before, with the hope that somebody with more CompSci experience would be able to tell me if/why this is a bad idea: can we use floats to order Core Data managed objects?

The situation is this:

For simplicity, let's say a School has many Teachers.

School >> Teacher

Generally, the order of Teachers will stay the same (1, 2, 3, 4, 5), but on occasion, I will, for instance, want to move Teacher number 5 in between Teacher 1 and Teacher 2.

The normal way to create an index, using integers, would mean I would then need to re-order four of the five models. What I'm wondering is, what if I used a float to order the models? Then, for our five Teacher models, they would begin like this:

t1.order = 1.0;

t2.order = 2.0;

t3.order = 3.0;

t4.order = 4.0;

t5.order = 5.0;

And when I want to move t5 in between t1 and t2, I perform this operation:

t5.order = ( t1.order + t2.order ) / 2.0;

So the new list looks like:

t1.order = 1.0;

t5.order = 1.5;

t2.order = 2.0;

t3.order = 3.0;

t4.order = 4.0;

I now have my list sorted as I want it, and only had to update a single record. I can even move t3 between t5 and t2:

t3.order = ( t5.order + t2.order ) / 2.0;

t1.order = 1.0;

t5.order = 1.5;

t3.order = 1.75;

t2.order = 2.0;

t4.order = 4.0;

There must be a reason why this isn't the way. 开发者_如何学CGranted, as you sort, and sort, and sort, you'll end up with very long floats, and probably run out of precision at some point, but every so often, you could reset the order to 1.0, 2.0, 3.0 ... n.0.

Can someone talk me out of this?


This is a reasonable approach, given the limitation that you've already pointed out: the potential for collisions due to precision limits. Of course, you could stick with integers and start by indexing by increments of, say, 10000.

In either case, you will need to be able to detect a collision and to take necessary action when that happens. Since you are really just concerned with "ordinality", you could also recalibrate your indices from time to time. If set of objects is short enough, you could sort them by existing 'order' into an array and then iterate through array assigning new 'order' values at specified increments.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜