我试图创建一个NSDictionary
完整的数组在我的模型的实现文件中,但我的代码还没有工作。我想创建一些数组,它们是狗和猫的类型列表,然后使用名为DOG
和CAT
的键将这些数组添加到字典中。这是我的代码:为模型数据填充NSDictionary和NSArrays
@implementation wordDictionary
@synthesize catList = _catList;
@synthesize dogList = _dogList;
@synthesize standardDictionary =_standardDictionary;
- (void)setCatList:(NSMutableArray *)catList
{
self.catList = [NSMutableArray arrayWithObjects:@"lion", @"puma", @"snow leopard", nil];
}
- (void)setDogList:(NSMutableArray *)dogList
{
self.dogList = [NSMutableArray arrayWithObjects:@"pit bull", @"pug", @"chihuahua", nil];
}
-(void)setStandardDictionary:(NSMutableDictionary *)standardDictionary
{
[self.standardDictionary setObject: _catList forKey:@"CAT"];
[self.standardDictionary setObject: _dogList forKey:@"DOG"];
}
- (NSString*)selectKey
{
NSInteger keyCount = [[self.standardDictionary allKeys] count];
NSInteger randomKeyIndex = arc4random() % keyCount;
NSString *randomKey = [[self.standardDictionary allKeys] objectAtIndex:randomKeyIndex];
return randomKey;
}
@end
此代码是模型。模型连接到我的视图控制器,以便当用户点击按钮时,从randomKey
返回的NSString
显示在屏幕上的标签中。所以文本将会读取CAT
或DOG
。下面是该代码:
- (IBAction)changeGreeting:(UIButton*)sender {
NSString *chosenKey = [self.dictionary selectKey];
NSString *labelText = [[NSString alloc] initWithFormat:@"%@", chosenKey];
self.label.text = labelText;
}
不幸的是,当我点击模拟器上我得到一个错误信息,说按钮:Thread 1:EXC_ARITHMETIC (code=EXC_1386_DIV, subcode=0x0)
在NSInteger randomKeyIndex = arc4random() % keyCount;
,看来,我得到它,因为既不是我NSArray
也不是我NSDictionary
有任何在它们内部的对象。
有没有人有任何想法为什么我的NSArray
和NSDictionary
尚未填充?
非常感谢。
也是一个好点 – 2012-03-05 01:57:57