Use of int, NSInteger, NSUInteger, and NSNumber for iOS development

Source: Internet
Author: User

1. When int type variables are required, you can use int or NSInteger, just like the program that writes C, but NSInteger is recommended, in this case, you do not need to consider whether the device is 32-bit or 64-bit.
2. NSUInteger is unsigned, that is, there is no negative number, and NSInteger is signed.
3. Some people say that since NSInteger and other basic types exist, why does NSNumber exist? Of course, their functions are different.
NSInteger is a basic type, but NSNumber is a class. If you want to store a value, NSInteger cannot be used directly. For example, in an Array, NSInteger is used as follows:
NSArray * array = [[NSArray alloc] init];
[Array addObject: 3]; // compilation Error
This will cause compilation errors because NSArray requires a class, but '3' is not. NSNumber is required at this time:
NSMutableArray * array = [[NSMutableArray alloc] init];
[Array addObject: [NSNumber numberWithInt: 3];

There will be a warning for the two lines of code because NSArray is immutable.
NSArray * array1 = [[NSArray alloc] init];
[Array1 addObject: [NSNumber numberWithInt: 3];
Cocoa provides the NSNumber class for packaging (that is, implemented in the form of objects) Basic data types.
For example:
+ (NSNumber *) numberWithChar: (char) value;
+ (NSNumber *) numberWithInt: (int) value;
+ (NSNumber *) numberWithFloat: (float) value;
+ (NSNumber *) numberWithBool: (BOOL) value;
After encapsulating the basic data type into NSNumber, you can obtain it again using the following instance method:
-(Char) charValue;
-(Int) intValue;
-(Float) floatValue;
-(BOOL) boolValue;
-(NSString *) stringValue;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.