How do I check for an existing item in an NSSet or NSCountedSet?

I am currently populating model objects in NSSet (maybe I should be using NSCountedSet). Models must be unique. What I am doing is pull them out of the web service and then create them on the client side and add them to the collection.

My problem is this: there are times when I only pull out one model and add it to a set, for example, let's say I have a Ferrari inventory. So I will ask my server to pull me in one particular Ferrari because the person clicks on that detailed view of the Ferrari from the inventory. The Ferrari Custom Detail View will list all the different paints available for this model. So as soon as the user drills this Ferrari view, I will ask the server for all the paints available for a particular Ferrari model.

The user then goes back and then goes to the view controller, which asks for all paint colors available for each car. I already have Ferrari paints available in my wallet. Now I ask for ALL paints from the server. What is the best way to combine existing paints with all paints without duplicating resources?

0


a source to share


2 answers


What you need is a way to uniquely identify each object from the server. In a database, an object (part or whole) can be represented as a row, and the rowid is usually a monotonically increasing integer (although your data source might be using something else). In any case, store this unique ID in every object you create and check for an object with this ID before creating a new object. If the object already exists, return the existing object, and if not, create a new object and store it in the cache. Using integers as IDs works great because you can use NSMapTable as cache with rowids as keys and values ​​are pointers to objects.



+2


a source


Maintain NSArray*

in your application that stores objects NSString*

based on some hash function of your functions:

hashValue = hash(color + horsepower + leatherSeating + whatever...)

      

For example, you can take the hash of an SHA1

ordered string ( example code ).



Take the functions you get from the web service and generate a hashed value from them using the same function.

Find your application hash table for the web service value using -containsObject:

.

If it returns YES

, do X, otherwise do Y.

0


a source







All Articles