我是一个新的开发人员创建一个简单的“字典”应用程序供个人使用,我的问题是关于如何在我的特定情况下正确实现模型 - 视图 - 控制器设计。请为我提供必要的背景:模型 - 视图 - 控制器在iPhone字典应用上的实践
我希望能够点击按钮并在屏幕的一侧显示一个单词,并让另一个标签在另一侧显示一个关联单词列表侧。例如:当我点击按钮时,我想让主标签显示“猫”,并为列表显示“老虎”,“雪豹”,“狮子”等。输出将是随机的:显示的标签是随机的,列表将被加密。
我已经在Xcode 4.3控制台中通过将每个列表存储在NSMutableArray中并使用NSDictionary来保存所有NSArrays来实现此输出。下面是代码:
//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的工作原理。
我想知道如果这种理解是正确的,如果任何人有任何指示如何组织我的模型数据最有效地得到我想要的输出。
非常感谢您的帮助!我卡住了!
哇,谢谢你花时间写这样一个彻底的答案@Ravin!我非常感谢你的洞察力,我将检查你所引用的系列讲座。 – 2012-03-01 07:12:10
确实如此。 @Orpheus:不要忘记接受答案,这不可能让你得到更好的答案:) – 2012-03-01 14:07:33