views:

43

answers:

2

So, I want to put an instance variable into a NSString like this:

NSString *theAnswer = (@"The answer is %@\n", self.answer);

I'm not sure am I right or not. I thought that NSString would work like NSLog but apparently it doesn't.

theAnswer returns as only the instance variable without "The answer is"

Can someone tell me why and how to fix this problem?

Thanks.

+1  A: 
NSString *theAnswer = [NSString stringWithFormat:@"The answer is %@", self.answer];
dj2
Thank You, that worked.
theAmateurProgrammer
@theAmateurProgrammer: You should accept his answer then.
thyrgle
A: 

I would also like to note in addition to dj2 answer that NSLog is a method not an Object. Objects are not initialized in the form of ("param1", param2) For the case of NSString you do what dj2 did:

NSString *theAnswer = [[NSString alloc] initWithFormat:@"The answer is %@", self.answer];

Where you have to declare theAnswer as a NSString pointer, because all Objective-C objects are pointers, then say again what class it is going to be allocated under (in this case NSString) then you say how you are going to initialize it and in this case you are using initWithFormat: to initialize it.

thyrgle
Thank You for your answer. I do want to ask what difference would it make if I initialized NSString or not?
theAmateurProgrammer
@theAmeratureProgrammer: I actually, asked a question after this, initializing it this way will not dealloc it automatically, but the other way will do that. So, take your pick.
thyrgle