Can't get russian letters in EXIF

2019-08-14 06:36发布

问题:

example 1 - it works

NSString *first = @"Russian letters(Русские буквы)";
[exifDictionary setValue:first  forKey:(NSString*)kCGImagePropertyExifUserComment];

example 2 - doesn't work

NSString *rus = @"Русские буквы";
NSString *first;
first = [[NSString alloc] initWithFormat:@"Russian letters(%@)",rus]; 

[exifDictionary setValue:first  forKey:(NSString*)kCGImagePropertyExifUserComment];

In second case in EXIF write "Russian letters(??????? ?????)" if NSString contains parameter its happens. how can I get correct russian letters use NSString with parameter?

maybe problem is the next saving at dictionary?

[exifDictionary setValue:[NSString stringWithFormat:@"Russian letters(%@)",rus]  forKey:(NSString*)kCGImagePropertyExifUserComment];

or

[exifDictionary setValue:first  forKey:(NSString*)kCGImagePropertyExifUserComment];

回答1:

Using UTF8 hard-coded strings in code isn't safe. See apple's article about Formatting String Objects.

I suppose that you can use that code as workaround:

NSString *rus = @"Русские буквы";
NSString *formatString = [NSString initWithUTF8String:"Russian letters(%@)"];
NSString *first = [[NSString alloc] initWithFormat:formatString, rus];

Or if that doesn't work either, so, you can always use plain C to perform formatting:

NSString *rus = @"Русские буквы";
char buffer[128];
snprintf(buffer, 128, "Russian letters(%s)", [rus cStringUsingEncoding:NSUTF8Encoding]);
NSString *first = [[NSString alloc] initWithUTF8String:buffer];