[英]How to use NSArray and NSDictionary?
I'm learning iOS from iTunes U and trying to build a programmable calculator. 我正在从iTunes U学习iOS ,并试图构建一个可编程计算器。 I have added three variables which the user can use to allot values.
我添加了三个变量,用户可以使用它们分配值。 I understand that the variables would be passed as
NSString
objects and then the user would touch the numbers which would be passed as NSNumbers
and allotted to the variables. 我知道变量将作为
NSString
对象传递,然后用户将触摸将作为NSNumbers
传递并分配给变量的数字。 I don't understand how to use NSArrays
and NSDictionary
to allot the numbers to these variables. 我不明白如何使用
NSArrays
和NSDictionary
将数字分配给这些变量。 Sorry for being a complete newbie, but I am not comfortable with the Documentation right now, so it is kind of fuzzy! 很抱歉,您是一个完整的新手,但是我现在对文档不满意,所以有点模糊! This is my code for appending digits on a
UILabel
and then using it for calculations: 这是我的代码,用于在
UILabel
上附加数字,然后将其用于计算:
- (IBAction)digitPressed:(UIButton *)sender {
NSString *digit = [sender currentTitle];
if (self.userIsInTheMiddleOfEnteringANumber) {
self.display.text = [self.display.text stringByAppendingFormat:digit];
everythingBrainLabel.text = [self.everythingBrainLabel.text stringByAppendingFormat:digit];
} else {
self.display.text = digit;
self.everythingBrainLabel.text = [self.everythingBrainLabel.text stringByAppendingFormat:@" %@", digit];
self.userIsInTheMiddleOfEnteringANumber = YES;
}
}
I can get the values of the variables in an NSMutableArray
but how to allot numbers here by simply pressing the digits after pressing the variable? 我可以在
NSMutableArray
获取变量的值,但是如何在按变量后仅按数字来分配数字呢? I added NSLog
just to check if variables were being passed and they show up in the console after I press the respective variable. 我添加了
NSLog
只是为了检查是否传递了变量,并在按下相应的变量后将它们显示在控制台中。
- (IBAction)variablePressed:(UIButton *)sender {
NSString *variablePressed = [sender currentTitle];
NSMutableArray *variableValues = [NSMutableArray arrayWithObjects:variablePressed, nil];
for(int i = 0; i < [variableValues count]; i++) {
NSLog(@"%@",[variableValues objectAtIndex:i]);
}
}
To set specific value for specific keys, you could add an NSMutableDictionary to your current class Add it as a property in your class and synthesize it Now when you want to assign a value for "x" you would do the following 要为特定键设置特定值,可以在当前类中添加NSMutableDictionary并将其作为类中的属性添加并合成它现在,当您要为“ x”分配值时,可以执行以下操作
//Add this var in your .h file create a property around it
NSMutableDictionary *variables;
//in the .m @synthesize variables;
When assigning the variable "x" 分配变量“ x”时
//for example you want to set varialbe "x" = 20
int xValue = 20;
NSString *xVariable = @"x";
[variables setObject:[NSNumber numberWithInt:xValue] forKey:xVariable];
Getting value for "x" 获得“ x”的价值
//Later on if you want to get x
NSString *xVariable = @"x";
int xValue = [[variables valueForKey:xVariable] intValue];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.