我试图NSDictionary
在我的模型的实现文件中创建一个完整的数组,但我的代码还没有工作。我想创建作为狗和猫类型列表的数组,然后将这些数组添加到带有名为DOG
and的键的字典中CAT
。这是我的代码:
@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
此代码是模型。该模型连接到我的视图控制器,这样当用户点击一个按钮时,NSString
返回的randomKey
内容会显示在屏幕上的标签中。因此文本将显示为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)
atNSInteger randomKeyIndex = arc4random() % keyCount;
并且似乎我得到了它,因为 myNSArray
和 myNSDictionary
里面都没有任何对象。
有谁知道为什么我的NSArray
和NSDictionary
没有被填充?
非常感谢。