Generating random numbers in Objective-C

前端 未结 13 2558
孤街浪徒
孤街浪徒 2020-11-22 02:07

I\'m a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:

Random.nextInt(74)
         


        
13条回答
  •  半阙折子戏
    2020-11-22 02:18

    I thought I could add a method I use in many projects.

    - (NSInteger)randomValueBetween:(NSInteger)min and:(NSInteger)max {
        return (NSInteger)(min + arc4random_uniform(max - min + 1));
    }
    

    If I end up using it in many files I usually declare a macro as

    #define RAND_FROM_TO(min, max) (min + arc4random_uniform(max - min + 1))
    

    E.g.

    NSInteger myInteger = RAND_FROM_TO(0, 74) // 0, 1, 2,..., 73, 74
    

    Note: Only for iOS 4.3/OS X v10.7 (Lion) and later

提交回复
热议问题