我是一名新开发人员,正在创建一个简单的“字典”应用程序供个人使用,我的问题是如何在我的特定情况下正确实现模型-视图-控制器设计。请耐心等待我的必要背景:
我希望能够点击一个按钮并让一个标签在屏幕的一侧显示一个单词,并让另一个标签在另一侧显示一个相关单词的列表。
例如:当我点击按钮时,我希望主标签显示“猫”,列表显示“老虎”、“雪豹”、“狮子”等。输出将是随机的:显示的标签将是随机,列表将被打乱。
我通过将每个列表存储在 NSMutableArray 中并使用 NSDictionary 保存所有 NSArray,在 Xcode 4.3 控制台中实现了此输出。这是代码:
//creates lists
NSArray *catList = [NSArray arrayWithObjects:@"Lion", @"Snow Leopard", @"Cheetah", nil];
NSArray *dogList = [NSArray arrayWithObjects:@"Dachshund", @"Pitt Bull", @"Pug", nil];
...
//creates dictionary and stores lists values with dictionary keys
NSMutableDictionary *wordDictionary = [[NSMutableDictionary alloc] init];
[wordDictionary setObject: catList forKey:@"Cats"];
[wordDictionary setObject: dogList forKey:@"Dogs"];
...
//randomizes selection of dictionary key
NSInteger keyCount = [[wordDictionary allKeys] count];
NSInteger randomKeyIndex = arc4random() % keyCount;
//displays selected key, which is the main word
NSLog(@"%@", randomKey);
//selects array list corresponding to key
NSMutableArray *randomlySelectedArray = [wordDictionary objectForKey:randomKey];
//shuffles the output of the selected word list array
for( int index = 0; index < keyCount; index++ )
{
int randomIndex = arc4random() % keyCount;
[randomlySelectedArray exchangeObjectAtIndex:index withObjectAtIndex:randomIndex];
}
//prints word list and removes displayed dictionary selection
NSLog(@"%@", randomlySelectedArray);
[wordDictionary removeObjectForKey:randomKey];
(我需要添加确实显示一个主要单词并一次列出一个的代码,也许使用 NSTimer,但这是我到目前为止所得到的。)
在 Xcode 中使用单视图模板,通过将其中一些代码添加到我的视图控制器实现文件中按钮的 IBAction 方法,我已经能够让模拟器显示一个主词和相应的列表。(当然,我将 NSLog 更改为 initWithFormat。)但是,我的随机化代码都不起作用。
最后,我的问题是如何分离事物以使它们最符合 MVC 设计?我在想:我的按钮和我的两个标签构成了视图。我的视图控制器是控制器,我的 NSArrays 和 NSDictionary 数据是模型。
但是,我一直将所有模型数据保存在视图控制器中,我很确定这是错误的。我认为我需要弄清楚如何为我的 NSArrays 和 NSDictionary 创建一个类来存储我的模型数据。然后我必须设法让我的按钮和标签通过我的视图控制器显示我的模型数据的所需文本。至少我认为这就是 MVC 的工作方式。
我想知道这种理解是否正确,以及是否有人对如何最有效地组织我的模型数据以获得我想要的输出有任何指示。
非常感谢您的帮助!我被困住了!