0

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.

user1424508
  • 3,231
  • 13
  • 40
  • 66
  • 2
    Please don't tag general iOS- and Objective-C programming-related questions with `xcode`, it is **highly inappropriate.** –  Mar 28 '13 at 07:15
  • 1
    @H2CO3 yeah! every day I get couple of posts having this **Xcode tag**, don't know why people can't make different in language(Objective c) and IDE(Xcode) – swiftBoy Mar 28 '13 at 07:18
  • @user1424508 the exception message says, you are trying to fetch the data from empty array, please!! check the array (like array length etc.) before fetching the data – swiftBoy Mar 28 '13 at 07:20
  • 1
    @RDC Surprisingly often they can't, and also very often they don't even make the effort distinguishing between Xcode, Objective-C, iOS, the Cocoa Touch APIs, the compiler, etc. It's very annoying and it should not be like this... :-( Only if they knew I'm making iOS apps without having ever touched Xcode... –  Mar 28 '13 at 07:21
  • @RDC I understand what the error message means. My issue is a design problem. how do i pull data from my backend api to my uiviewcontrollers without it crashing. Its processed on a different thread so by the time the backend data is loaded into my ios app the main thread has crashed. If it was a table view I could initiate the ivs on my uiviewcontrollers with a null value and then reload my tableview once the data is loaded from the backend but how can I do this with uiviewcontrollers? – user1424508 Mar 28 '13 at 21:33

1 Answers1

2

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.

zadr
  • 2,505
  • 18
  • 19