文字列の配列を含むプロパティ リスト ファイルを作成できます。たとえば、 という plist ファイルを作成し、words.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)];
これには次の利点があります。
plist ファイルはローカライズ可能であるため、plist をロードするコードを変更することなく複数の言語に翻訳できます。
データとコードを別々に保つことをお勧めします。
単語のリストは、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