Problem: Need Unique Identifier

I'm saving a custom object using NSArchiver. It retains all of my objects data, however, everytime I archive and unarchive it gives them new addresses

"<Item: 0x17005d070>",
"<Item: 0x17005e4b0>",
"<Item: 0x17005e4e0>"

"<Item: 0x170059fe0>",
"<Item: 0x170059ec0>",
"<Item: 0x17005a0a0>"

For the same 3 objects.

This causes problems because I need to hold a copy of some of the items and persist this copy, and later compare the copy to the original for equality [currentItem isEqual:oldItem]; Even when this should return true (i.e. the object is the same in terms of name, location, etc.) it will return false because the pointers are different. What's the solution to this? I've thought about adding a uniqueID to each object and then just storing that uniqueID, but that seems like overkill for what I'm trying to do.

Solution:

You can't rely on an objects memory address as a unique identifier. Use NSUUID.

有帮助吗?

解决方案

The problem is that you have not implemented isEqual: for your Item class. Implement it. Otherwise, as you've observed, we fall back on NSObject's definition of isEqual:, which is identicality (i.e. these are one and the same object). It is up to you to tell Cocoa that an Item should return true if the object is the same in terms of name, location, etc.; it doesn't magically know this.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top