Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top