Search code examples
objective-cmultithreadingafnetworkingafjsonrequestoperation

How do I pull JSON from afnetworking to provide data for an object without it crashing


I am using afnetworking to grab JSON data from my rest api. From that JSON data I create UIViewControllers based on how many items are in the array. For example if my JSON data has 3 items, then 3 UIViewControllers are created and added as childviews for a slider object I'm creating.

The problem is since the data from afnetworking finishes loading separately from my main thread, the program crashes because there is no data going to create my UIViewControllers.

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -   [__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'.

How do I address this problem? I read that I can use [operation waitUntilFinished] to stop the main thread from running until all the data is loaded by my server but people recommended against this.


Solution

  • You definitely don't want to block the main thread. Thats bad; it makes it look like your app is frozen.

    It sounds like you want to have a "loading" screen. This way, you could do something like post a notification when your data is ready. Your loading screen's view controller would then be observing that notification and then present the rest of the data when it comes in.