将环境变量替换为NSString

时间:2014-05-01 11:36:56

标签: cocoa nsstring nsregularexpression

我试图将环境变量替换为字符串,但regularExpresionWithPattern停滞不前。

我在另一个问题上找到了一些似乎可以回答别人问题的代码,但无论出于何种原因,这些问题都不适用于我:

NSString *substituteVariables(NSString *input) {
    NSDictionary *environment = [[NSProcessInfo processInfo] environment];

    NSError *error = nil;
    // I know this pattern isn't good enough, but it's a start!
    NSRegularExpression *regex = [NSRegularExpression
        regularExpressionWithPattern:@"$([A-Z_]+)"
        options:NSRegularExpressionCaseInsensitive error:&error];
    return [regex stringByReplacingMatchesInString:input options:0
                  range:NSMakeRange(0, input.length)
                  usingBlock:^NSString *(NSTextCheckingResult *result, 
                                         NSMatchingFlags flags, BOOL *stop) {
        NSString *envKey = [input substringWithRange:[result rangeAtIndex:1]];
        return [environment objectForKey:envKey];
    }];
};

这会生成一个编译器警告,该警告会大量表明代码无法正常工作:

appbundler/native/main.m:64:19: warning: instance method '-stringByReplacingMatchesInString:options:range:usingBlock:' not found (return type defaults to 'id') [-Wobjc-method-access]
    return [regex stringByReplacingMatchesInString:input options:0 range:NSMakeRange(0, input.length) usingBlock:^NSString *(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSRegularExpression.h:25:12: note: receiver is instance of class declared here
@interface NSRegularExpression : NSObject <NSCopying, NSCoding> {
           ^
1 warning generated.

我正在构建针对OS 10.8 SDK的版本,尽管该代码也可以用于10.7 SDK。

我检查了文档,实际上,这种方法并不存在于文档中。但不知何故,它对其他人有用,我无法弄明白为什么。

1 个答案:

答案 0 :(得分:1)

如果有人成功使用了某种方法,但它不在SDK中,那么他们必须添加一个类别。我注意到另一个问题是实现了这个确切的方法:Is this a sane Objective-C Block Implementation?