0

私はこの言語(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;

等々...

しかし、ライブラリのように別のファイルで作成し、それぞれに長い文を含む何百もの「ケース」を作成する代わりに、それを「スイッチ」にインクルード/インポートできるかどうか疑問に思います。

あなたが私の言いたいことを理解してくれることを願っています。

前もって感謝します!

4

3 に答える 3

1

単語を配列に入れ、arc4random_uniform を使用して配列内のインデックスを選択する必要があります。switch ステートメントは必要ありません。

于 2013-02-11T05:05:06.580 に答える
1

文字列の配列を含むプロパティ リスト ファイルを作成できます。たとえば、 という plist ファイルを作成し、words.plistXcode の組み込み 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. 単語のリストは、Web サーバーを含め、任意の URL から読み込むことができます。

例として:

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
于 2013-02-11T05:13:44.710 に答える
0

すべての文字列を NSArray に入れてから、次を使用してランダムなオブジェクトを取得できます

arrayWithStrings[arc4random_uniform(arrayWithStrings.count)];

JSON または plist ファイルにすべての文字列がある場合は、NSJSONSerializationまたは[NSArray arrayWithContentsOfURL:]

于 2013-02-11T05:06:14.570 に答える