.Net 与 Cocoa 字符串格式

发布于 2024-10-13 04:58:53 字数 1240 浏览 2 评论 0原文

我可以重现以下 C#/.NET:

//A
String.Format("There are {0} cats in my {1} and no {2}", 2, "house", "dogs");

in Objective-C/Cocoa:

//B
[NSString stringWithFormat:@"There are %d cats in my %@ and no %@", 2, "house", "dogs"];

但我不能这样做:

//C
String.Format("I have {0} dogs in my house.  My {0} dogs are very nice, but it is hard to walk {0} dogs at the same time.", numDogs);

in Objective-C:

//D
[NSString stringWithFormat:@"I have %d dogs in my house.  My %d dogs are very nice, but it is hard to walk %d dogs at the same time.", numDogs];

因为它使用 printf 格式或其他格式。有更先进的方法吗?有什么方法可以在字符串解析中进行 KVC 吗?

从技术上讲,这就是我想要的:

[player setValue:@"Jimmy" forKey@"PlayerName"];
//later
[NSString stringWithMagicFormat:@"<PlayerName> sat on a bench in the middle of winter, and <GenderPronoun> felt very cold." andPlayer:player];
// or
[NSString stringwithMagicFormat: playerEnteredStringWithTagInIt andPlayer:player];

但我会满足:

String.Format(playerEnteredStringWithTagInIt, player.PlayerName, player.PlayerGender, player.GenderPronoun, ...);

谢谢,

I can reproduce the following C#/.NET:

//A
String.Format("There are {0} cats in my {1} and no {2}", 2, "house", "dogs");

in Objective-C/Cocoa:

//B
[NSString stringWithFormat:@"There are %d cats in my %@ and no %@", 2, "house", "dogs"];

But I can't do this:

//C
String.Format("I have {0} dogs in my house.  My {0} dogs are very nice, but it is hard to walk {0} dogs at the same time.", numDogs);

in Objective-C:

//D
[NSString stringWithFormat:@"I have %d dogs in my house.  My %d dogs are very nice, but it is hard to walk %d dogs at the same time.", numDogs];

because it uses the printf format or whatever. Is there a more advanced way of doing this? Is there some way of doing KVC in string-parsing?

This is technically what I'd like:

[player setValue:@"Jimmy" forKey@"PlayerName"];
//later
[NSString stringWithMagicFormat:@"<PlayerName> sat on a bench in the middle of winter, and <GenderPronoun> felt very cold." andPlayer:player];
// or
[NSString stringwithMagicFormat: playerEnteredStringWithTagInIt andPlayer:player];

But I'll settle for:

String.Format(playerEnteredStringWithTagInIt, player.PlayerName, player.PlayerGender, player.GenderPronoun, ...);

Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

铃予 2024-10-20 04:58:53
[NSString stringWithFormat:@"I have %1$d dogs in my house.  My %1$d dogs are very nice, but it is hard to walk %1$d dogs at the same time.", numDogs];

(参见man 3 printf。)

[NSString stringWithFormat:@"I have %1$d dogs in my house.  My %1$d dogs are very nice, but it is hard to walk %1$d dogs at the same time.", numDogs];

(See man 3 printf.)

鹊巢 2024-10-20 04:58:53

如果您使用 NSStringstringWithFormat:,那么我认为 C99 合规性并不真正适用:而 stringWithFormat: 与 printf 类似,它有自己的实现,并且已经存在了一段时间。

NSLocalizedString() 宏实际上会自动为您完成此操作。例如,假设我有以下代码:

 @implementation MDAppController

- (id)init {
    if (self = [super init]) {
        NSArray *catsArray = [NSArray array];
        NSString *string = [NSString stringWithFormat:
         NSLocalizedString(@"There are %lu %@ %@ in my home.", @"no comment"),
        (unsigned long)[catsArray count],
                            NSLocalizedString(@"red", @""),
                            NSLocalizedString(@"cats", @"")];
        NSLog(@"string == %@", string);
    }
    return self;
}

@end

中运行以下代码

如果我随后在终端/usr/bin/genstrings ~/Developer/NSLocalizedString/MDAppController.m -o ~/Desktop/Strings

(尽管我我更喜欢将窗口标题栏中的代理图标拖到我保存在 Dock 中的 AppleScript Droplet 上:GenerateStrings。它将生成的 .strings 文件(覆盖)写入 ~/Desktop/Strings/(如果需要,您可以通过将其拖放到 AppleScript 编辑器来编辑脚本)。

它将生成一个 UTF16 Localized.strings 文件,您可以将其添加到您的项目中。其中将包含以下内容:

English.lproj/Localizable.strings

/* No comment provided by engineer. */
"cats" = "cats";

/* No comment provided by engineer. */
"red" = "red";

/* no comment */
"There are %lu %@ %@ in my home." = "There are %1$lu %2$@ %3$@ in my home.";

将其复制到西班牙语项目子文件夹并根据需要更改项目的顺序(因为在西班牙语中形容词通常位于名词之后):

Spanish.lproj/Localizable。 当英语是语言和字符串

/* No comment provided by engineer. */
"cats" = "gatos";

/* No comment provided by engineer. */
"red" = "rojos";

/* no comment */
"There are %lu %@ %@ in my home." = "Está %1$lu %3$@ %2$@ en mi casa.";

中我的主要(最重要)语言时文本偏好窗格:

1/20/2011 12:59:37 PM NSLocalizedString[1777] string == There are 0 red cats in my home.

当西班牙语是我的主要(最重要)语言时;文本偏好窗格:

1/20/2011 12:37:02 PM NSLocalizedString[1702] string == Está 0 gatos rojos en mi casa。

.strings 文件在某种意义上是键值对。

有关详细信息,请参阅 资源编程指南:字符串资源

If you are using NSString and stringWithFormat:, then I don't think the C99 compliance really applies: while stringWithFormat: is similar to printf, it has its own implementation that has been around for a while.

The NSLocalizedString() macro actually does this for you automatically. For example, say I have the following code:

 @implementation MDAppController

- (id)init {
    if (self = [super init]) {
        NSArray *catsArray = [NSArray array];
        NSString *string = [NSString stringWithFormat:
         NSLocalizedString(@"There are %lu %@ %@ in my home.", @"no comment"),
        (unsigned long)[catsArray count],
                            NSLocalizedString(@"red", @""),
                            NSLocalizedString(@"cats", @"")];
        NSLog(@"string == %@", string);
    }
    return self;
}

@end

If I then run the following in Terminal

/usr/bin/genstrings ~/Developer/NSLocalizedString/MDAppController.m -o ~/Desktop/Strings

(Though I prefer just dragging the proxy icon in the window title bar onto this AppleScript droplet I keep in my Dock: GenerateStrings.app. It (over)writes the generated .strings files into ~/Desktop/Strings/ (creating it if necessary). You can edit the script by dropping it onto AppleScript Editor).

It will generate a UTF16 Localizable.strings file which you can add to your project. In it it will have the following:

English.lproj/Localizable.strings

/* No comment provided by engineer. */
"cats" = "cats";

/* No comment provided by engineer. */
"red" = "red";

/* no comment */
"There are %lu %@ %@ in my home." = "There are %1$lu %2$@ %3$@ in my home.";

Duplicate it to a Spanish language project sub folder and change the order of items as necessary (since in Spanish adjectives usually come after the noun):

Spanish.lproj/Localizable.strings

/* No comment provided by engineer. */
"cats" = "gatos";

/* No comment provided by engineer. */
"red" = "rojos";

/* no comment */
"There are %lu %@ %@ in my home." = "Está %1$lu %3$@ %2$@ en mi casa.";

When English is my primary (topmost) language in Language & Text pref pane:

1/20/2011 12:59:37 PM NSLocalizedString[1777] string == There are 0 red cats in my home.

When Spanish is my primary (topmost) language in Language & Text pref pane:

1/20/2011 12:37:02 PM NSLocalizedString[1702] string == Está 0 gatos rojos en mi casa.

The .strings files are in a sense key value pairs.

For more info see Resource Programming Guide: String Resources

嗫嚅 2024-10-20 04:58:53

我喜欢每个人的答案,但我只花了 15 分钟在文档中找到了我正在寻找的答案......叹息,RTM!这是我的解决方案,以防其他人正在寻找类似的东西。

// Put this in a category of NSString
- (NSString*) stringByReplacingOccurrencesOfKeysWithValues:(NSDictionary*)keyValuePairs
{
    NSString *fStr = self;
    if (keyValuePairs) {
        for (NSString *key in [keyValuePairs allKeys]) {
            NSString *value = [NSString stringWithFormat:@"%@",[keyValuePairs valueForKey:key]];
            fStr = [fStr stringByReplacingOccurrencesOfString:key withString:value];
        }
    }
    return fStr;
}

似乎工作正常,这是我的测试代码:

// testing NSString+Keys
NSMutableDictionary *mud = [NSMutableDictionary dictionaryWithCapacity:1];
[mud setValue:@"Jimmy" forKey:@"{PlayerName}"];
[mud setValue:[NSNumber numberWithInt:97] forKey:@"{HitPoints}"];
[mud setValue:[NSNumber numberWithFloat:1.0678f] forKey:@"{meters}"];
NSString *mystr = [@"Help me {PlayerName} before it is too late! I only have {HitPoints}hp left!  And I am {meters}m away! {PlayerName} hurry!" stringByReplacingOccurrencesOfKeysWithValues:mud];
NSLog(mystr);

输出是:

在为时已晚之前帮助我吉米!我只剩下97马力了!而我距离1.0678m!吉米快点!

I like everyone's answers, but I just spent 15 minutes in the Docs and found the answer I was looking for... sigh, RTM! Here's my solution in case anyone else is looking for something similar.

// Put this in a category of NSString
- (NSString*) stringByReplacingOccurrencesOfKeysWithValues:(NSDictionary*)keyValuePairs
{
    NSString *fStr = self;
    if (keyValuePairs) {
        for (NSString *key in [keyValuePairs allKeys]) {
            NSString *value = [NSString stringWithFormat:@"%@",[keyValuePairs valueForKey:key]];
            fStr = [fStr stringByReplacingOccurrencesOfString:key withString:value];
        }
    }
    return fStr;
}

Seems to work fine, this was my test code:

// testing NSString+Keys
NSMutableDictionary *mud = [NSMutableDictionary dictionaryWithCapacity:1];
[mud setValue:@"Jimmy" forKey:@"{PlayerName}"];
[mud setValue:[NSNumber numberWithInt:97] forKey:@"{HitPoints}"];
[mud setValue:[NSNumber numberWithFloat:1.0678f] forKey:@"{meters}"];
NSString *mystr = [@"Help me {PlayerName} before it is too late! I only have {HitPoints}hp left!  And I am {meters}m away! {PlayerName} hurry!" stringByReplacingOccurrencesOfKeysWithValues:mud];
NSLog(mystr);

Output was:

Help me Jimmy before it is too late! I only have 97hp left! And I am 1.0678m away! Jimmy hurry!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文