2016-06-09 1 views
3

Objective C에서 python'sstr.format 메서드와 비슷한 문자열 형식을 지정하는 방법이 있습니까? @"this is {keyword_1}, and this is {keyword_2}" 키워드로 문자열을 가져 와서 @{@"keyword_2": @"bar", @"keyword_1": @"foo"} 사전을 사용하여 해당 키워드를 바꿔서 새로운 문자열 @"this is foo, and this is bar"을 생성하고 싶습니다. 아니,키워드 별 Objective-C 문자열 형식

[NSString stringWithKeywordFormat:@"hello {user_name}, today is {day_of_week}!" keywords:@{@"user_name":@"Jack", @"day_of_week":@"Thursday"}]; 
+1

처럼 보이는 내장 어디에도 없습니다. [GRMustache] (https://github.com/groue/GRMustache) 템플릿 라이브러리는 비슷한 것을 구현하는 것처럼 보이지만 (결코 사용하지 않았습니다.) – omz

+0

@omz. 포인터 주셔서 감사. 제가 확인하겠습니다. –

답변

2

NSScanner 클래스를 사용하여 형식 문자열을 구문 분석하는 것과 같은 함수를 작성하는 것이 매우 쉽습니다.

는 .H 파일에 NSString에 카테고리를 선언 :

#import <Foundation/Foundation.h> 

@interface NSString (KeywordFormat) 
+ (NSString *)stringWithKeywordFormat:(NSString *)format keywords:(NSDictionary *)dictionary; 
@end 

하는 .m 파일의 구현이

#import "NSString+KeywordFormat.h" 

@implementation NSString (KeywordFormat) 

+ (NSString *)stringWithKeywordFormat:(NSString *)format keywords:(NSDictionary *)dictionary 
{ 
    NSMutableString *result = [NSMutableString string]; 

    NSScanner *scanner = [NSScanner scannerWithString:format]; 
    [scanner setCharactersToBeSkipped:nil]; 

    NSString *temp; 
    while (![scanner isAtEnd]) 
    { 
     // copy characters to the result string until a { is found 
     if ([scanner scanUpToString:@"{" intoString:&temp]) 
      [result appendString:temp]; 
     if ([scanner isAtEnd]) 
      break; 

     // swallow the { character 
     if (![scanner scanString:@"{" intoString:NULL]) 
      break; 
     if ([scanner isAtEnd]) 
      break; 

     // get the keyword 
     if (![scanner scanUpToString:@"}" intoString:&temp]) 
      break; 
     if ([scanner isAtEnd]) 
      break; 

     // swallow the } character 
     if (![scanner scanString:@"}" intoString:NULL]) 
      break; 

     // lookup the keyword in the dictionary, and output the value 
     [result appendFormat:@"%@", dictionary[temp]]; 
    } 

    return([result copy]); 
} 

@end 
+0

변수의 시작을 나타내지 않는 문자열에 리터럴'{'을 넣는 방법이 있어야합니다. – rmaddy

+1

@rmaddy 동의 함. 나는 그 부분을 독자를위한 운동으로 남기기로 결정했다. – user3386109

0

하지 표준 첫째 자 애플 라이브러리 :

은 목표 C에서,이 같은 보일 수 있습니다. 제 3 자 라이브러리에서도 본 적이 없습니다.