Escaping the @“ ” characters in Objective C

只愿长相守 提交于 2020-01-03 03:04:12

问题


I'm trying to set the background image of a view based on a passed "artistID." Here is my code so far:

 NSString *backgroundImageName = [[NSString alloc]initWithFormat:@"artistbackground%i.png",_artistID];


    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:backgroundImageName]];
    NSLog(@"%@",backgroundImageName);

unfortunately, for the parameter in ImageNamed, I'm passing in: artistibackground1

instead of:

@"artistbackgound1"

Any ideas on how to escape the @ and the quotes??

Thanks!!


回答1:


self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[NSString stringWithFormat:@"@%@",backgroundImageName]];

Essentially make two strings, it will add the @"" in the second.




回答2:


You should use \ before the character you want. An example:

NSLog(@"\@\"Try\"");

The code prints

@"Try"



回答3:


Don't forget that even string constants are NSString objects in Objective-C. This is part of the magic! I frequently see programmers new to the language writing this line:

[NSString stringWithFormat:@"@%@",backgroundImageName];

But you can simplify this line to:

[@"@" stringByAppendingString:backgroundImageName];

Magic!



来源:https://stackoverflow.com/questions/9930053/escaping-the-characters-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!