创建随机数
调用arc4random()来创建随机数. 还可以通过random()来创建, 但是必须要手动的设置seed跟系统时钟绑定。这样才能够确保每次得到的值不一样。所以相比较而言arc4random()更好一点。
定时器
下面的这个定时器会每分钟调用一次调用myMethod。
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(myMethod)
userInfo:nil
repeats:YES];
target:self
selector:@selector(myMethod)
userInfo:nil
repeats:YES];
当我们需要给定时器的处理函数myMethod传参数的时候怎么办?用"userInfo"属性。
1. 首先创建一个定时器:
[NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(myMethod)
userInfo:myObject
repeats:YES];
target:self
selector:@selector(myMethod)
userInfo:myObject
repeats:YES];
2. 然后传递NSTimer对象到处理函数:
-(void)myMethod:(NSTimer*)timer {
// Now I can access all the properties and methods of myObject
[[timer userInfo] myObjectMethod];
}
// Now I can access all the properties and methods of myObject
[[timer userInfo] myObjectMethod];
}
用"invalidate"来停止定时器:
[myTimer invalidate];
myTimer = nil; // ensures we never invalidate an already invalid Timer
myTimer = nil; // ensures we never invalidate an already invalid Timer