Include a variable inside a NSString?

怎甘沉沦 提交于 2019-11-30 17:40:47

问题


This works fine, we all know that:

NSString *textoutput = @"Hello";
outLabel.text = textoutput;

However, what if you want to include a variable inside that NSString statement like the following:

NSString *textoutput =@"Hello" Variable;

In C++ I know when I cout something and I wanted to include a variable all I did was soemthing like this:

cout << "Hello" << variableName << endl;

So I'm trying to accomplish that with Objective-C but I don't see how.


回答1:


You can do some fancy formatting using the following function:

NSString *textoutput = [NSString stringWithFormat:@"Hello %@", variable];

Note that %@ assumes that variable is an Objective-C object. If it's a C string, use %s, and if it's any other C type, check out the printf reference.

Alternatively, you can create a new string by appending a string to an existing string:

NSString *hello = @"Hello";
NSString *whatever = [hello stringByAppendingString:@", world!"];

Note that NSString is immutable -- once you assign a value, you can't change it, only derive new objects. If you are going to be appending a lot to a string, you should probably use NSMutableString instead.




回答2:


I have The Cure you're looking for, Robert Smith:

if your variable is an object, use this:
NSString *textOutput = [NSString stringWithFormat:@"Hello %@", Variable];

The '%@' will only work for objects. For integers, it's '%i'.

For other types, or if you want more specificity over the string it produces, use this guide



来源:https://stackoverflow.com/questions/7550588/include-a-variable-inside-a-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!