Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include a variable inside a NSString?

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.

like image 620
rs14smith Avatar asked Sep 26 '11 04:09

rs14smith


People also ask

Is NSString UTF 8?

An NSString object can be initialized from or written to a C buffer, an NSData object, or the contents of an NSURL . It can also be encoded and decoded to and from ASCII, UTF–8, UTF–16, UTF–32, or any other string encoding represented by NSStringEncoding .

How to declare string variable in Objective-C?

NSString *myNSString = [NSString stringWithFormat:@"test"]; NSString *myRetainedNSString = [[NSString alloc] initWithFormat:@"test"]; Or if you need an editable string: NSMutableString *myMutableString = [NSMutableString stringWithFormat:@"test"];

What is NSString in Objective-C?

(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.


2 Answers

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.

like image 51
RavuAlHemio Avatar answered Oct 11 '22 20:10

RavuAlHemio


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

like image 36
Jordaan Mylonas Avatar answered Oct 11 '22 22:10

Jordaan Mylonas