0

I am developing an application for the iphone that, in viewDidLoad, calls arc4random to get a random number. My problem is that each time the application starts, it gets the same number from arc4random. I ought to point out that I see this behaviour when I test the app on my iphone device and start the application from the device touchscreen. If I run the app on the device from xcode, then I see different random numbers.

Any help or advice would be appreciated. Thanks.

  • 2
    `arc4random` should seed itself automatically, this is why there is no explicit seed function. In fact, you should never be seeing this behaviour. Can you post some code? – Mike Weller May 03 '13 at 10:07
  • Just for completeness, the line of code is "int chosen_book = (arc4random() % numberOfBooks) + 1;" (where numberOfBooks is also an int with value 66) – Simon Courtenage May 03 '13 at 10:09
  • Does this code only run when the app starts? If the app isn't terminated but runs in the background, your application:didFinishLaunching: (for example) will not be called subsequent times, whereas Xcode will force a termination before running. – Mike Weller May 03 '13 at 10:20
  • the code runs in the controller's viewDidLoad method. I quit the app by pressing the home button on the phone. – Simon Courtenage May 03 '13 at 10:23
  • viewDidLoad will only be called once until a memory warning occurs. On iOS 6 it will only ever be called once. When you press the home button, your app is not terminated. The next time you tap the icon, the previous instance is opened. – Mike Weller May 03 '13 at 10:24
  • Mike - that's great! Thanks. if you want to post that as an answer, I'll upvote it and mark it as accepted. Thanks again. – Simon Courtenage May 03 '13 at 10:31

1 Answers1

2

arc4random does not need seeding and should not be returning the same results each time you call it.

From your comments, it seems to me that your code is not being executed each time your app comes to the foreground. Remember that when you press the home button your app is not terminated by default. It will enter the background, and will resume when you tap the icon again.

If your code is inside viewDidLoad, it will only be called once which means your variable will not be updated and will contain the same value each time you inspect it. When you run from Xcode your app will be fully terminated each time and you will get the expected behaviour.

You should probably put your code in viewWillAppear: or viewDidAppear: so it is called whenever the view appears on screen, rather than once when your view initially loads.

Mike Weller
  • 45,401
  • 15
  • 131
  • 151