从plist生成随机名称

时间:2010-06-22 16:34:46

标签: iphone objective-c plist

我想从我创建的plist中读取一个forenames和surnames的列表,然后为'Person'类随机选择一个forename和一个姓氏。

plist有这种结构;

Root (Dictionary)
-> Names (Dictionary)
--> Forenames (Array)
---> Item 0 (String) "Bob"
---> Item 1 (String) "Alan"
---> Item 2 (String) "John"
--> Surnames (Array)
---> Item 0 (String) "White"
---> Item 1 (String) "Smith"
---> Item 2 (String) "Black"

我已经能够输出字典的所有键,但我不确定如何获取“Forenames”或“Surnames”键,然后将其存储在数组中。

输出所有键的代码是日志的简单输出。

即;

// Make a mutable (can add to it) dictionary
NSMutableDictionary *dictionary;


// Read foo.plist
NSString *path      = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"foo.plist"];

dictionary = [NSDictionary dictionaryWithContentsOfFile:finalPath];

// dump the contents of the dictionary to the console
for (id key in dictionary)
{
    NSLog(@"Bundle key=%@, value=%@", key, [dictionary objectForKey:key]);      
}

NSMutableArray *forenames;

// This doesn't work, it outputs an empty array
forenames = [dictionary objectForKey:@"Forenames"];
NSLog(@"Forenames:%@", forenames);

问题;

  1. 如何让我的NSMutableArray * forenames采用字典'Forenames'的内容?

  2. 一旦我在他们自己的NSMutableArrays中存储了forename和surname,我需要随机选择一个forename和一个姓氏;最好的方法是什么?

  3. 我的想法是我可以创建一个带有Forename / Surname类变量的Person.m文件,我可以创建随机生成的人。

    感谢。

1 个答案:

答案 0 :(得分:3)

根据你的plist的结构,我认为你需要再做一个解除引用的程度:

NSDictionary *names = [dictionary objectForKey:@"Names"];
NSMutableArray *forenames = [[names objectForKey:@"Forenames"] mutableCopy];
NSMutableArray *surnames = [[names objectForKey:@"Surnames"] mutableCopy];

然后,您可以使用srandomrandom为数组生成随机索引。在[0,N)上生成随机数的一般方法是:

NSUInteger i = (NSUInteger)((random()/(double)RAND_MAX)*N);

通过调用数组的count替换上面的N,您将被设置。

顺便说一句,我看不出创建名称数组的可变副本的原因。我只是想说明你是如何做到的。此外,您需要使用srandom(time(NULL));播种,以便在每次程序运行时获得不同的随机值。

相关问题