sprintf对NSString的功能

Joh*_*hnK 0 cocoa printf objective-c nsstring

如何获得sprintfObjective-C 的功能?该函数当然是stdioC语言的一部分,所以我当然可以调用它,但是因为我使用的是Foundation,所以我也需要它来使用它NSString.

编辑

我为我的不明智而道歉,但我实际上希望更像是返回字符串的PHP sprintf 函数.(在Josh Caswell非常有效地编辑我的问题之前,这可能是稍微明显的.)这可能是NSLog但不是写入控制台而是将字符串(或指针)作为返回值.

das*_*ght 6

这确实在可可同样的事情最接近的功能NSStringstringWithFormat.

使用sprintf:

char buf[100];
sprintf(buf, "Line %d of %d", currentLine, totalLines);
Run Code Online (Sandbox Code Playgroud)

运用 stringWithFormat:

NSString res = [NSString stringWithFormat:@"Line %d of %d", currentLine, totalLines];
Run Code Online (Sandbox Code Playgroud)

请注意,stringWithFormat:支持使用%@格式说明符打印Cocoa对象.