Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an object is NSInteger

I hope to check the type of an object, for NSString:

[theObject isKindOfClass:[NSString class]]

it works, but for NSInteger

[theObject isKindOfClass:[NSInteger class]]

will report error

Welcome any comment

like image 746
monsabre Avatar asked Aug 24 '11 04:08

monsabre


People also ask

How do I check if NSInteger is null?

Functions to check nil or null object input for NSNumber and NSString. @return If nil input or null object input found, a NSNumber object with zero value will return. If the input is a NSStirng object, a NSNumber object contianing dobleValue of the string will return.

Can NSInteger be nil?

Actually by default in many situations an NSInteger will be nil, because nil is the same as zero... you may well get a compiler warning though. In the sample code given previousScore would be 0 (nil) if [self score] came back nil...

What is NSNumber in Objective C?

NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char , short int , int , long int , long long int , float , or double or as a BOOL .

Why use NSNumber?

The purpose of NSNumber is simply to box primitive types in objects (pointer types), so you can use them in situations that require pointer-type values to work. One common example: you have to use NSNumber if you want to persist numeric values in Core Data entities.


3 Answers

Use the NSNumber class:

if ([obj isKindOfClass:[NSNumber class]]) { ... }

NSNumber Inherits from NSValue : NSObject

NSInteger Used to describe an integer.

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
#else
typedef int NSInteger;
#endif
like image 68
Book Of Zeus Avatar answered Oct 16 '22 04:10

Book Of Zeus


NSInteger is not an Objective-C class. It's a typedef for an integral type. As such, an object is never going to be a NSInteger.

What you're looking for is the NSNumber class, which is an Objective-C class.

like image 22
Etienne de Martel Avatar answered Oct 16 '22 05:10

Etienne de Martel


NSInteger is not an object type. It's a foundation data type. Checkout Foundation Data Types Reference to see how it is defined.

like image 32
gsempe Avatar answered Oct 16 '22 05:10

gsempe