引数の場所の指定ができる
+ (instancetype)stringWithFormat:(NSString *)format
objective-cで文字列を生成する↑のメソッド。
%[引数番号]$@
のように指定すると引数を任意の場所に挿入することができる。
びっくり。
NSString *sampleStr = [NSString stringWithFormat:@"%1$@くんと%2$@ちゃんが歩いていました。%1$@くんはお花を持っていました", @"タカシ", @"ハナコ"];
//=>タカシくんとハナコちゃんが歩いていました。タカシくんはお花を持っていました
どこで役に立つ?
私はautolayoutのVFLを指定する時に使ってます。
Viewの指定を取り回しできるので楽。
//VFLで文字列をまとめる
NSString *horizontalFormat = [NSString stringWithFormat:@"H:|-20-[%@]-20-|", topViewKey];
NSString *addHorizontalFormat = [NSString stringWithFormat:@"H:|-20-[%1$@]-20-[%2$@(==%1$@)]-20-|", leftViewKey,rightViewKey];
NSString *verticalFormat = [NSString stringWithFormat:@"V:|-88-[%1$@]-20-[%2$@(==%1$@)]-20-|", topViewKey, leftViewKey];
NSString *addVertivalFormat = [NSString stringWithFormat:@"V:|-88-[%1$@]-20-[%2$@(==%1$@)]-20-|", topViewKey, rightViewKey];
以上です!