Include a variable inside a NSString?

允我心安 提交于 2019-11-30 22:19:19

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.

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

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