PDA

View Full Version : Converting float to NSString




liptonlover
Jan 14, 2009, 10:19 AM
Here's the code...

- (void)sendVariable:(float)variable toOutlet:(id)outlet {
[outlet setText:variable];
}

Here's the error.
error: incompatible type for argument 1 of 'setText:'

The text property in UILabel accepts NSStrings only but I need it to display float values. I looked under NSString but couldn't find anything such as 'stringFromDouble' so I don't know what to do.

Also... I got this warning.
warning: conflicting types for '-(void)sendVariable:(float)variable toOutlet:(id)outlet'

I don't understand what this warning means. Can anyone help?
Thanks in advance, Nate



dejo
Jan 14, 2009, 10:24 AM
Look into using stringWithFormat.

jeremy.king
Jan 14, 2009, 10:29 AM
^
|
|
what he said

liptonlover
Jan 14, 2009, 10:37 AM
Ok, here's the code now.
- (void)sendVariable:(float)variable toOutlet:(id)outlet {
[string initWithFormat:@"%f"];
[string setValue:variable];
[outlet setText:string];
[string release];
}
I have one more problem. Now that I've formatted the NSString instance, I don't know how to give it a value. It doesn't have a setValue: property or method, nor does it have a setText: one. Sorry if I'm missing something painfully obvious, it wouldn't be the first time.

jnic
Jan 14, 2009, 10:42 AM
Ok, here's the code now.
- (void)sendVariable:(float)variable toOutlet:(id)outlet {
[string initWithFormat:@"%f"];
[string setValue:variable];
[outlet setText:string];
[string release];
}
I have one more problem. Now that I've formatted the NSString instance, I don't know how to give it a value. It doesn't have a setValue: property or method, nor does it have a setText: one. Sorry if I'm missing something painfully obvious, it wouldn't be the first time.

http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/Strings/Articles/FormatStrings.html

- (void)sendVariable:(float)variable toOutlet:(id)outlet {
[outlet setText:[NSString stringWithFormat:@"%f", variable]];
}

liptonlover
Jan 14, 2009, 11:20 AM
Thanks, I didn't know stringWithFormat could then accept a variable as a second argument.
Thanks, Nate

jnic
Jan 14, 2009, 11:34 AM
Thanks, I didn't know stringWithFormat could then accept a variable as a second argument.
Thanks, Nate

NSString behaves in roughly the same way as C's printf (http://en.wikipedia.org/wiki/Printf#1970s:_C.2C_Lisp) so will take as many arguments as you care to add.

liptonlover
Jan 14, 2009, 12:23 PM
Thanks :)
Cheers, Nate