NSNumber: is a class that handles numbers in OC
Nsvalue is a subclass of NSNumber
How to handle:
Wrap the int,float,double into an object
Benefits of using NSNumber:
You can save data of a basic data type to an array or dictionary
// define basic data types
int a = 10;
float b = 2.2f;
double d = 1.22;
int x = 100;
// int is wrapped as NSNumber
NSNumber * intObj = [NSNumber numberWithInt: a];
NSMutableArray * array = [NSMutableArray arrayWithObjects: intObj, nil];
// float is wrapped into NSNumber
NSNumber * floatObj = [NSNumber numberWithFloat: b];
// add objects to the array
[array addObject: floatObj];
// double is wrapped into NSNumber
NSNumber * doubleObj = [NSNumber numberWithDouble: d];
// add objects to the array
[array addObject: doubleObj];
// @ 值 , Wrap values into objects, a quick and easy way
[array addObject: @ (x)];
NSLog (@ "% @", array);
// Add the first and second elements of the array
NSNumber * n1 = array [0]; // remove the 0th element
int a1 = [n1 intValue];
NSNumber * n2 = array [1]; // remove the first element
float a2 = [n2 floatValue];
// a1 = a1 + a2;
// concise
a1 = [array [0] intValue] + [array [1] floatValue];
NSLog (@ "% d", a1);
Nsvalue: Mainly used to wrap pointers, cgrect structures, etc. into OC objects for storage
CGPoint p1 = CGPointMake (3, 5);
CGRect r1 = CGRectMake (0, 3, 5, 9);
NSMutableArray * arr = [NSMutableArray array];
// p1 is wrapped into obj
NSValue * pointValue = [NSValue valueWithPoint: p1];
// Store objects in an array
[arr addObject: pointValue];
// wrap r1 into NSValue object
[arr addObject: [NSValue valueWithRect: r1]];
NSLog (@ "% @", arr);
// take out the value of r1
NSValue * r1Value = [arr lastObject];
NSRect r2 = [r1Value rectValue];
NSLog (@ "% @", NSStringFromRect (r2));
Packaging struct
// define date structure
typedef struct Date
{
int year;
int month;
int day;
} MyDate;
int main (int argc, const char * argv []) {
@autoreleasepool {
// year month day
MyDate nyr = {2015, 9, 11};
// @encode (MyDate) function, generate a constant string description of the MyDate type
NSValue * val = [NSValue valueWithBytes: & nyr objCType: @encode (MyDate)];
// define an array and store val in it
NSMutableArray * arr = [NSMutableArray arrayWithObject: val];
/ *
Remove NSValue object from the array
From the object, get the value of the structure variable
Pass the address of a structure variable
* /
MyDate tmd;
[val getValue: & tmd];
NSLog (@ "% d,% d.% D", tmd.year, tmd.month, tmd.day);
OBJECTIVE-C (Foundation framework One NSNumber (Nsvalue))