Reputation: 13
This is something that I'm truly baffled by: when I initialize a string with format with two different variables like this
Order *o = [orders objectAtIndex:i];
NSString *line = [[NSString alloc] initWithFormat:(@"%@;%@\n", [o _length], [o _amount])];
and then print it out with
NSLog(@"%@", line);
it shows up like this:
tableviewtest[4812:123250] 200
Which is wrong. However if I do the same by doing this
NSLog(@"%@;%@\n", [o _length], [o _amount]);
it comes out like this:
tableviewtest[4812:123250] 120cm;200
Which is how I'd WANT the line
to be. Why is this happening? I need it to be in the same format as the line
so that I can then write it into a text file later.
EDIT:
_length
and _amount
are @property NSString *_length
in an Order-class. orders
is an NSMutableArray
that houses the data to an NSTableView
, where the data is put in with NSComboBoxes and NSTextFields. Compiler also gives a warning: Format string is not a string literal (potentially insecure).
Upvotes: 0
Views: 273
Reputation: 16660
@Schemetrical is correct, but it is not a compiler confusion. It is a behavior defined in the C standard. Let's have the original source code:
NSString *line = [[NSString alloc] initWithFormat:(@"%@;%@\n", [o _length], [o _amount])];
The arg list is build from
(@"%@;%@\n", [o _length], [o _amount])
This is a expression build from comma operators following the C standard, 6.5.17.. That means that
@"%@;%@\n", [o _length]
is evaluated as
((void)@"%@;%@\n")
expr = [o _length]
returning expr. Then
(expr, [o _amount])
is evaluated as
((void)expr)
expr = [o _amount])
This is the result of the expression used as single argument:
NSString *line = [[NSString alloc] initWithFormat:_amount];
Therefore the whole statement is pretty good C/Objective-C code. The only reason to show a warning is that the format arg is not a constant. (But this is definitely not what went wrong.)
Upvotes: 2
Reputation: 5536
Instead of
NSString *line = [[NSString alloc] initWithFormat:(@"%@;%@\n", [o _length], [o _amount])];
,
use NSString *line = [NSString stringWithFormat:@"%@;%@\n", [o _length], [o _amount]];
Upvotes: 1