If someone uses a method successfully, but it's not in the SDK, they must've added it with a category. I notice this other question has an implementation of that exact method: Is this a sane Objective-C Block Implementation?
Substituting environment variables into NSString
-
13-07-2023 - |
Pregunta
I'm trying to substitute environment variables into a string, but am stalled by regularExpresionWithPattern
.
I found some code on another question which appeared to answer someone else's question, but for whatever reason, doesn't work for me:
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];
}];
};
This generates a compiler warning which heavily suggests that the code won't work:
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.
I'm building against the OS 10.8 SDK though the code is expected to work against the 10.7 SDK as well.
I have checked the docs and indeed, this method doesn't exist in the docs. Yet somehow it worked for someone else, and I can't quite figure out why.
Solución
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow