1

本の名前をキーとして保持するために、この plist を辞書として作成しました。

<dict>
    <key>Frankestein</key>
        <dict>
        <key>0</key>
        <string>his name was frank</string>
        <key>1</key>
        <string>he was a monster</string>
    </dict>
    <key>dracula</key>
    <dict>
        <key>0</key>
        <string>his name was dracula</string>
        <key>1</key>
        <string>he was a vampire</string>
    </dict>
</dict>
</plist>

次に、plist を辞書にロードします。

NSDictionary *plisttext2 = [NSDictionary dictionaryWithContentsOfFile:@"text2.plist"];

辞書からランダムな文を生成して表示し、文番号と書籍名 (キー) を表示するにはどうすればよいですか?

ご協力いただきありがとうございます!!

4

2 に答える 2

1

1つは、機能しNSDictionary *plisttext2 = [NSDictionary dictionaryWithContentsOfFile:@"text2.plist"];ません。このContentsOfFileパラメーターは、相対パスのファイル名ではなく、絶対パスを想定しています。これを行うには、次を使用します。

NSBundle* bundle = [NSBundle mainBundle];
NSString* plistPath = [bundle pathForResource:@"text2" ofType:@"plist"];
NSDictionary* plisttext2 = [NSDictionary dictionaryWithContentsOfFile:plistPath];

ランダムな文を生成して表示するには、すべてのキーを追跡する必要があります。

NSArray* keys = [plisttext2 allKeys]

次に、インデックスを使用してランダム キーを選択します。

int randomIndex = arc4random() % (keys.count);
NSString* key = [plisttext2 objectForKey:[keys objectAtIndex:randomIndex]];

ランダムに選択されたキーを使用して、本の文章にアクセスし、同じ方法でランダムに選択できます。選択後、それらをすべて足し合わせると、結果が得られます。

これは、異なる本からランダムな文を生成できることを意味しますが、文番号 + 本名を表示することもできます (それらを参照するインデックスを保持しているため)。

于 2012-10-24T13:41:55.617 に答える
0

plist を反復処理して各辞書の最大キー値を決定し、以下のコードと同様のことを行って、各辞書から文をランダムに選択できます。

int min = 0; 
int max = iterationResult;
int randNum = rand() % (max-min) + max; //create the random number.
NSLog(@"RANDOM NUMBER: %i", randNum); 
于 2012-10-24T13:37:28.647 に答える