gpt4 book ai didi

iphone - 如何创建要导入的库而不是在 Objective-C 中使用 switch 语句?

转载 作者:行者123 更新时间:2023-11-28 22:40:01 26 4
gpt4 key购买 nike

我是这门语言 (Objective-C) 的新手。我的目的是创建一个带有随机句子的 iOS 应用程序。一切都已完成,现在我只是使用以下代码随机化单词。

-(IBAction)randText:(id)sender {

int text;
text = rand()% 6;

switch (text) {
case 0:
textLabel.text = @"Ett";
break;
case 1:
textLabel.text = @"Två";
break;

等等……

但是,我想知道我是否可以在单独的文件中创建类似库的内容,并将其包含/导入到“开关”中,而不是制作数百个每个句子都较长的“案例”。

希望你明白我的意思。

提前致谢!

最佳答案

您可以创建一个包含字符串数组的属性列表文件。例如,创建一个名为words.plist 的plist 文件,然后使用Xcode 内置的plist,编辑器将根对象设置为数组,并向数组添加行。你可以加载它:

NSURL *plistURL = [[NSBundle mainBundle] URLForResource:@"words" withExtension:@"plist"];
NSArray *words = [NSArray arrayWithContentsOfURL:plistURL];

// pick a random word:
NSString *randomWord = [words objectAtIndex:arc4random_uniform(words.count)];

这有以下好处:

  1. plist 文件是可本地化的,因此无需修改加载 plist 的代码即可将其翻译成多种语言。

  2. 尝试将数据和代码分开是个好主意。

  3. 单词列表可以从您想要的任何 URL 加载,包括从 Web 服务器加载。

举个例子:

MyAppDelegate.h

@interface MyAppDelegate : NSObject <UIApplicationDelegate>
@property NSArray *words;
// ... and your other properties as well
@end

MyAppDelegate.m

@implementation MyAppDelegate

- (void) applicationDidFinishLaunching:(UIApplication *) app
{
NSURL *plistURL = [[NSBundle mainBundle] URLForResource:@"words" withExtension:@"plist"];
self.words = [NSArray arrayWithContentsOfURL:plistURL];
}

- (NSString *) pickRandomWord
{
return [self.words objectAtIndex:arc4random_uniform(self.words.count)];
}

- (NSString *) makeRandomSentence
{
NSMutableString *result = [NSMutableString string];
for (NSUInteger i = 0; i < 10; i++)
[result appendFormat:@"%@ ", [self pickRandomWord]];
return result;
}

@end

关于iphone - 如何创建要导入的库而不是在 Objective-C 中使用 switch 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14806124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com