如何将textField的integerValue放入数组?

时间:2014-11-14 10:17:42

标签: ios objective-c iphone arrays for-loop

@property NSMutableArray*textFieldsA;

@property NSMutableArray*textFieldsB;

@property NSMutableArray*textFieldsR;

@property NSMutableArray *operandArrayA;

@property NSMutableArray *operandArrayB;

_textFieldsA = @[self.textFieldA0, self.textFieldA1, self.textFieldA2, self.textFieldA3, self.textFieldA4, self.textFieldA5, self.textFieldA6, self.textFieldA7, self.textFieldA8];
_textFieldsB = @[self.textFieldB0, self.textFieldB1, self.textFieldB2, self.textFieldB3, self.textFieldB4, self.textFieldB5, self.textFieldB6, self.textFieldB7, self.textFieldB8];
_textFieldsR = @[self.textFieldR0, self.textFieldR1, self.textFieldR2, self.textFieldR3, self.textFieldR4, self.textFieldR5, self.textFieldR6, self.textFieldR7, self.textFieldR8];

for (int i = 0; i < 9; i++) {
    _operandA = [((UITextField*)_textFieldsA[i]).text integerValue];
    _operandB = [((UITextField*)_textFieldsB[i]).text integerValue];
    [self.arithmetic setOperandA:_operandA operandB:_operandB operator:_operator];
    _finalString = [NSString stringWithFormat:@"%d",[self.arithmetic result]];
    ((UITextField*)_textFieldsR[i]).text = _finalString;
}

我怎么能把整数值

 self.textFieldA0.text , self.textFieldA1.text , self.textFieldA3.text ........self.textFieldA8.text

进入数组(operandArrayA)?

我试过了

 operandArrayA[i] = [((UITextField*)_textFieldsA[i]).text integerValue];

但它不起作用,我该怎么办?

2 个答案:

答案 0 :(得分:2)

很遗憾,您无法在NSArray中添加原始数据类型。您需要为整数值创建NSNumber的对象。将此对象存储到数组中。

像这样:

NSNumber *number = @([((UITextField*)_textFieldsA[i]).text  integerValue]);
operandArrayA[i] = number;

答案 1 :(得分:0)

您需要分配并初始化所有数组。如下所示

     operandArrayA=[[NSMutableArray alloc]init];
     operandArrayB=[[NSMutableArray alloc]init];

    //if u want to store strings

    [operandArrayA  addObject:((UITextField*)_textFieldsA[i]).text];
    [operandArrayB addObject:((UITextField*)_textFieldsB[i]).text];

     //(OR) if u want to store integer value then u need to convert to NSNumber

     [operandArrayA  addObject:[NSNumber numberWithInt:[((UITextField*)_textFieldsA[i]).text integerValue]]];
    [operandArrayB addObject:[NSNumber numberWithInt:[((UITextField*)_textFieldsB[i]).text integerValue]]];

   //(OR)

   operandArrayA[i]=[NSNumber numberWithInt:[((UITextField*)_textFieldsA[i]).text integerValue]];
   operandArrayB[i]=[NSNumber numberWithInt:[((UITextField*)_textFieldsB[i]).text integerValue]];

希望它可以帮助你..