开发者

Concatenating Objective-C NSStrings

开发者 https://www.devze.com 2023-02-21 04:39 出处:网络
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开发者_高级运维\"];

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?


stringByAppendingString: or stringWithFormat: pretty much is the way.


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];


Have you looked into NSMutableString ?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消