连接 Objective-C NSString

发布于 2024-10-29 10:32:22 字数 529 浏览 1 评论 0原文

我是 Objective-C 的新手,所以请耐心等待。这就是我连接 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];

它有效,但看起来很草率。这是连接 NSString 的理想方法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

倾城°AllureLove 2024-11-05 10:32:22

stringByAppendingString:stringWithFormat: 几乎就是这样。

stringByAppendingString: or stringWithFormat: pretty much is the way.

转身以后 2024-11-05 10:32:22

您可以一次附加多个路径组件。例如:

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

您还可以在单​​个字符串中指定整个路径:

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

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];
前事休说 2024-11-05 10:32:22

您是否研究过 NSMutableString< /a>?

Have you looked into NSMutableString ?

鱼窥荷 2024-11-05 10:32:22

常见的约定是使用 [NSString stringWithFormat:...] 但它不执行路径追加 (stringByAppendingPathComponent)。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文