Question

I'm trying to take the output of arc4sin and put it into a label.

(EDIT: You can ignore this and just post sample code, if this is too irrelevant.)

I've tried:

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *number =  [[NSString alloc] stringWithFormat: @"%@", arc4random() % 9];
    label.text = number;
}

I've created an IBOutlet for "label" and connected it. What's wrong here?

Was it helpful?

Solution

In Cocoa format strings, %@ denotes an Objective-C object, which ints, floats, longs, and shorts all aren't. They are just C datatypes, and use their own formats, the exact same as in printf().

According to the manpage, arc4random() is defined as u_int32_t arc4random(void);, thus, you should use the %u format specifier (unsigned integer).

Edit: Thanks to Till for pointing this out: you want -initWithFormat: if you are calling -alloc, -stringWithFormat: is a class method of NSString.

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