使用块的返回值动态创建字符串

Sam*_*io2 2 string objective-c ios objective-c-blocks

所以我正在尝试动态构建一个字符串,我真的很喜欢构建这个字符串的所有代码都存在于作为参数传递给stringWithFormat方法的块中.以下代码示例应该演示我正在尝试实现的目标:

    NSString * deviceLanguage = [NSString stringWithFormat:@"Device Language: %@", ^NSString*(void){

        NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];

        NSString *locale = [[NSLocale currentLocale] objectForKey: NSLocaleCountryCode];

        return [NSString stringWithFormat:@"%@_%@", language, locale];

    }];
Run Code Online (Sandbox Code Playgroud)

预期的输出将是......

Device Language: en_GB
Run Code Online (Sandbox Code Playgroud)

但是,我从这个方法获得的输出实际上返回description了NSGlobalBlock方法,例如

Device Language: <__NSGlobalBlock__:0x30a35c>
Run Code Online (Sandbox Code Playgroud)

这是因为我没有在字符串中使用正确的占位符,或者没有声明该块返回一个NSString对象?

Mar*_*n R 6

那是因为你将块本身作为参数传递给stringWithFormat:,而不是调用块的结果:

NSString * deviceLanguage = [NSString stringWithFormat:@"Device Language: %@", ^NSString*(void){

    NSLocale *locale = [NSLocale currentLocale];
    NSString *language = [locale displayNameForKey:NSLocaleIdentifier
                         value:[locale localeIdentifier]];
    return [NSString stringWithFormat:@"%@_%@", language, locale];

}()];
Run Code Online (Sandbox Code Playgroud)

请注意,您可以使用"复合语句表达式" 而不是块来实现类似的结果:

NSString * deviceLanguage = [NSString stringWithFormat:@"Device Language: %@", ({

    NSLocale *locale = [NSLocale currentLocale];
    NSString *language = [locale displayNameForKey:NSLocaleIdentifier
                         value:[locale localeIdentifier]];
    [NSString stringWithFormat:@"%@_%@", language, locale];

})];
Run Code Online (Sandbox Code Playgroud)

  • 在第一种情况下,编写[NSString stringWithFormat:@"设备语言:%@",^ {...}()]就足够了; (2认同)