dallen
dallen

Reputation: 2651

Concatenating Objective-C NSStrings

I'm a total newbie at Objective-C, so bear with me. This is how I'm concatenating my URL:

id url      = [NSURL URLWithString:@"http://blahblah.com/gradient.jpg"];
id image    = [[NSImage alloc] initWithContentsOfURL:url];
id tiff     = [image TIFFRepresentation];

NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:  @"Desktop"];
NSString *fileToWrite = @"/test.tiff";
NSString *fullPath = [docsDir stringByAppendingString:fileToWrite];

[tiff writeToFile:fullPath atomically:YES];

It works, but it seems sloppy. Is this the ideal way of doing concatenating NSStrings?

Upvotes: 0

Views: 398

Answers (4)

Darren
Darren

Reputation: 25619

You can append multiple path components at once. E.g.:

NSString* fullPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/test.tiff"];

You can also specify the entire path in a single string:

NSString* fullPath = [@"~/Desktop/test.tiff" stringByExpandingTildeInPath];

Upvotes: 3

ryanprayogo
ryanprayogo

Reputation: 11817

Have you looked into NSMutableString ?

Upvotes: 1

Yann Ramin
Yann Ramin

Reputation: 33167

A common convention is to use [NSString stringWithFormat:...] however it does not perform path appending (stringByAppendingPathComponent).

Upvotes: 0

unexpectedvalue
unexpectedvalue

Reputation: 6139

stringByAppendingString: or stringWithFormat: pretty much is the way.

Upvotes: 3

Related Questions