2

I want to include <# #> in a literal string in an Objective C program. However, Xcode automatically replaces the string thinking it should be a placeholder as used in code snippets.

e.g.

NSString *pattern = @"<#foo#>"

Try putting this into Xcode and it redisplays as a placeholder for foo.

In the actual program the string is an RE like this <#(.*)#> and surprisingly, the code actually works as intended - the problem only manifests itself in the display in Xcode. The real problem is that this creates a fragile situation, it is far too easy to cause the text to be replaced accidentally when in the editor.

As a workaround I can construct the string from it's parts

NSString *p1 = @"<#(.*)";
NSString *p2 = @"#>";
NSString *pattern = [NSString stringWithFormat:@"%@%@",p1,p2];

but that is not very satisfactory.

Does anyone know a better way to override this behaviour in Xcode?

2 Answers 2

6

You can avoid the bad behavior by taking advantage of string concatenation, e.g.

NSString *str = @"<" "#foo#" ">";
3
  • @Tommy Xcode doesn't seem to care either way, and it's cleaner without all the extra '@'s. Aug 19, 2014 at 1:59
  • Then I guess I'm behind on Objective-C syntax changes. You got my +1 regardless.
    – Tommy
    Aug 19, 2014 at 2:18
  • 1
    You can concatenate Objective-C literal strings and C literal strings in this manner. Based on a test I just did, I believe it always uses the type of the first element. Aug 19, 2014 at 2:24
2

Swift 4, Xcode 9 - you just need to separate out or replace one character to make the sequence work. Still not perfect...

string concatenation:

let pattern = "<" + "#foo#>"

string interpolation:

let pattern = "\("<")#foo#>"

percent encoding:

let pattern = "%003c#foo#>".removingPercentEncoding

Funny fact: printing the pattern to the console displays as a placeholder, foo.

Not so funny fact: you can't print the pattern to a log. Since it's created via concatenation or other runtime processing, it doesn't meet the StaticString type required in a log message.

Update: you can use the pattern in a log (though, again, it displays as a placeholder - argh!). To get past the StaticString issue, you can use %@ in your log statement:

let pattern = "<" + "#foo#>" // or whichever version you like best
os_log("%@", log: .default, type: .debug, pattern)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.