Question

Let's say that you're modelling take-out restaurants in Core Data. Each Restaurant should have a phoneNumber property, but it will be different depending on the user's street address. Have no fear, though, there's a REST API that helps you to convert street addresses and restaurant IDs to phone numbers.

I would like to model the phoneNumber property of Restaurants such that the REST API is contacted:

  1. only as needed (ie. when the phoneNumber property is accessed)
  2. as infrequently as possible

The strategy I'm considering goes something like this:

  1. offer a KVO-compliant phoneNumberLoaded boolean on restaurants
  2. return nil when accessing phoneNumber in an unloaded state
  3. start to asynchronously load the phoneNumber property either:
    1. the first time it's accessed
    2. when the user calls a preloadPhoneNumber method
  4. maintain a queue that receives preload requests on behalf of the API, batching them up
  5. update the phoneNumber as the API calls return, setting phoneNumberLoaded to YES

Shall I get to work, or does anyone have a better strategy?

Était-ce utile?

La solution

I don't know if this is what you meant but this is how I see it:

Restaurant<<-->Address (city,street,needPhoneResolutoin[BOOL],phoneNumber[default value: nil])
Create a class that will handle resolution (PhoneResolver).
The resolver will have a FRC with entity: Address, predicate: needPhoneResolution == YES AND phoneNumber == nil.
implement the delegate methods, but handle only inserted objects (and all objects that exist after the first perform fetch call) and deleted objects (cleanup).
batch them up (at -controllerDidChangeContent:)
perform the REST fetch
update the DB.
report failure to resolver (another fetch will be needed, or mark the address as unresolvable).

This way, you don't need to implement yourself the queue or the KVO (provided by CoreData), and by principle of locality, if a user requested the phone once (and the fetch failed), you would still keep the user request for that phone and try to fetch it every time the resolver is started.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top