Jack Nutkins
Jack Nutkins

Reputation: 1555

Objective - C Rookie NSString Problem

I have this code:

// Fill out the email body text
NSString *emailBody = (@"Name:%@\nNumber of People:\nDate:", name.text);
NSLog(@"%@", emailBody);

As you can see I'm trying to append name.text to the e-mail body just after "Name:". However, NSLog only outputs the string contained in name.text and none of the rest of the e-mail body. What am I doing wrong here that the code deletes the rest of the string apart from name.text?

E.G if name.text contained the text "Jack", then NSLog would only output "Jack" and not:

Name: Jack
Number of People: x 
Date: x

Which is what I am looking for.

Can anyone give me an insight as to what I'm doing wrong?

Thanks,

Jack

Upvotes: 4

Views: 288

Answers (3)

johnbakers
johnbakers

Reputation: 24750

generally you want to either use stringWithFormat as was suggested, which creates an autorelease string that follows the format you have, or you can use initWithFormat instead, which creates a string you can manually manage for better memory behavior, if necessary.

some books will insist that for the iphone, which has limited memory, you don't depend on autorelease objects more than it absolutely necessary, so you'd often find this instead:

NSString *emailBody = [[NSString alloc] initWithFormat:@"Name:%@\nNumber of People:\nDate:", name.text];

Then you can use "emailBody" and immediately after you are done with it, put in this line:

[emailBody release];

This is a good habit to get into in general.

Upvotes: 0

Nickolay Olshevsky
Nickolay Olshevsky

Reputation: 14160

You should write

NSString *emailBody = [@"Name:%@\nNumber of People:\nDate:" stringByAppendingString:name.text];

Or, if it doesn't compile,

[[NSString stringWithString:@"Name:%@\nNumber of People:\nDate:"] stringByAppendingString:name.text]

Upvotes: 0

Vladimir
Vladimir

Reputation: 170829

Use +stringWithFormat method:

NSString *emailBody = [NSString stringWithFormat:@"Name:%@\nNumber of People:\nDate:", name.text];

What you have now is a valid code, but it doesn't do what you want:

(@"Name:%@\nNumber of People:\nDate:", name.text);

calls a comma operator - it evaluates its 1st parameter, discards it and returns 2nd parameter, so that's why emailBody is eventually filled with name.text value

Upvotes: 12

Related Questions