iphone アプリ 足し算引き算。

  • (IBAction)executeCalc:(id) sender {

int str = [income.text intValue];
int str2 = [cost.text intValue];
int str3 = str - str2;

[dpi setText:[NSString stringWithFormat:@"%d", str3]];
}

やっと足し算引き算ができた。オブジェクトCを習い始めて6ヶ月。
%dを使わないと整数値intが表現できないことに気がつく。
rubyの柔軟さは間違いなくない。変態言語OBJC。

つかえるかも

■プリミティブ型
プリミティブ型には NSNumber を使う。

例えば NSUInteger型 だと、

セットするとき

NSUInteger index = 15;
NSNumber *pIndex = [NSNumber numberWithUnsignedInteger:index]; // (1)

NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:pIndex forKey:@"index"];


という具合だ。

(1)でプリミティブ型の NSUInteger をいったん NSNumber のインスタンスにしている。
これで無事に NSMutableDictionary にセットできる。


次に、取り出すときはその逆を行う。


NSNumber *pIndex2 = (NSNumber *)[dic objectForKey:@"index"]; // (2)
// NSNumber *pIndex2 = [dic objectForKey:@"index"]; これでもOK。暗黙にキャストされる
NSUInteger index2 = [pIndex2 unsignedIntegerValue];

NSLog(@"%u", index2);


(2)でいったん NSNumber で取り出し、NSNumber numberWithUnsignedInteger: の逆で NSNumber unsignedIntegerValue すると元の NSUInteger に戻せる。
ほかのプリミティブ型に対応するためにはそれなりの名前でメソッドがあるので、コード補間を使って見るとだいたい分かると思う。

int型 を例に挙げると以下のようになる。

 int を NSNumber にするには NSNumber numberWithInt: を使う
 NSNumber を int にするには NSNumber intValue を使う

float型 でも同じような感じ。

型式文字列であればうまくゆく

  • (IBAction)executeCalc:(id) sender {

NSString*str = [income text ];
[dpi setText:[NSString stringWithFormat:@"%@", str]];
}

stringwithformatは数値は一切受け付けない。
floatのままではダメ、Rubyレベルの柔軟さはない。

以下バツ

  • (IBAction)executeCalc:(id) sender {

float str = [income text ];
[dpi setText:[NSString stringWithFormat:@"%@", str]];
}