C中将NSNumber转换为int

C中将NSNumber转换为int

本文介绍了在Object-C中将NSNumber转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将其添加到NSDictionary之前,我使用[NSNumber numberWithInt:42]@(42)将int转换为NSNumber:

I use [NSNumber numberWithInt:42] or @(42) to convert an int to NSNumber before adding it to an NSDictionary:

int intValue = 42;
NSNumber *numberValue = [NSNumber numberWithInt:intValue];
NSDictionary *dict = @{ @"integer" : numberValue };

当我从NSDictionary检索值时,如何将其从NSNumber转换回int?

When I retrieve the value from the NSDictionary, how can I transform it from NSNumber back to int?

NSNumber *number = dict[@"integer"];
int *intNumber = // ...?

它抛出一个异常,表示我以这种方式进行铸造时是必需的:

It throws an exception saying casting is required when I do it this way:

int number = (int)dict[@"integer"];

推荐答案

看看文档.使用intValue方法:

NSNumber *number = [dict objectForKey:@"integer"];
int intValue = [number intValue];

这篇关于在Object-C中将NSNumber转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:25