2015-04-12 73 views
-3
stack = [NSString stringWithFormat:@"%[email protected]%2$d", stack, number]; 

我跟着Xcode计算器教程,我不太确定%[email protected]%2$d代表什么。请指导我。

+2

[文档](https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Conceptual/Strings/Articles/ formatSpecifiers.html#// apple_ref/doc/uid/TP40004265-SW1) –

回答

1

这种格式是用来明确选择哪个参数应在字符串中被替换所以1$是第一个参数,2$为第二等...

'@'是ObjC对象(一般里显示对象的描述),并'd'是整数

在这种情况下,它也可以简单地写成:

stack = [NSString stringWithFormat:@"%@%d", stack, number]; 
+0

但是,它不是'$ 1',它是'1 $' – Logan

+0

我的错误已被更正。 – giorashc

+3

:) - 一定会做得太快! – Logan

-2
[NSString stringWithFormat:@"%[email protected]%2$d", stack, number]; 

逻辑上分解为意味着你想要一个字符串(你可以从格式的字符串中获得),显示两个项目(你可以从字符串之后的项目和格式中的%符号数量中看到它。

%1 $ @%2 $ d是两个项目,你可以用%,%1和%2分别表示第一个和第二个项目。

%1 $ @ - @表示时便会翻译成字符串

%2 $ d的对象 - d表示十进制。

+0

不确定为什么这个问题还没有关闭。或为什么人们不喜欢我的答案。 – nycynik

2

%@说参数是一个Objective-C对象,它发送一个描述选择器来获取将被插入到最终字符串中的字符串。

%[email protected]说同样的事情,但指定第一个参数。

%d是一个有符号的32位整数。

%2$d指定第二个参数是一个有符号的32位整数。

0

我假设你知道%@%d的含义。默认情况下,第一个说明符(如%@)将被参数列表中第一个参数的值替换,依此类推。但是,n$使您能够指定要在哪个位置使用其值来替换包含n$的说明符的参数。

事实上,一个简单的例子是更清晰:

NSString *aString = @"ultimate answer"; 
int anInteger = 42; 
NSLog(@"The %@ is %d.", aString, anInteger); // The ultimate answer is 42. 
NSLog(@"The %[email protected] is %2$d.", aString, anInteger); // The ultimate answer is 42. 
NSLog(@"%2$d is the %[email protected]", aString, anInteger); // 42 is the ultimate answer.