Document directory
Various numeric values
Both nsarray and nsdictionary can only store objects and cannot store any basic types of data, such as int, float, and struct. Therefore, we can use objects to encapsulate basic values.
Nsnumber
Cocoa provides nsnumber to store objects, but it cannot store various data in C. Therefore, we need to encapsulate some corresponding objects.
Nsnumber class to wrap basic data objects. You can use the following methods:
+ (Nsnumber *) numberwithchar: (char) value;
+ (Nsnumber *) numberwithint: (INT) value;
+ (Nsnumber *) numberwithfloat: (float) value;
+ (Nsnumber *) numberwithbool: (bool) value;
After you close a basic data type to nsnumber, you can obtain it again using the following instance method:
-(Char) charvalue:
-(INT) intvalue;
-(Float) floatvalue;
-(Bool) boolvalue;
-(Nsstring *) stringvalue;
Nsvalue
Nsnumber is actually a subclass of nsvalue. nsvalue can wrap any value. You can use nsvalue to put the structure into nsarray and nsdictionary, and create a new nsvalue using the following methods:
+ (Nsvalue *) valuewithbytes :( const void *) Values
Objctype :( constchar *) type;
The passed parameter is the address of the value you want to wrap (such as an nssize or your own struct ). Generally, you get the address of the variable you want to store. You can also provide a string to describe the data type, which is usually used to describe the type and size of the entity in struct. Add nsrect to nsarray as follows:
Nsrect rect = nsmakerect (1, 2, 30, 40 );
Nsvalue * value;
Value = [nsvalue valuewithbytes: & rect
Objctype: @ encode (nsrect)];
[Array addobject: value];
You can use getvalue: to provide a value:
-(Void) getvalue: (void *) vaule;
When getvalue is called, the address of the variable to store the value is passed:
Value = [array objectatindex: 0];
[Value getvalue: & rect];
Cocoa provides a convenient way to convert common struct data to nsvalue, as shown below:
+ (Nsvalue *) valuewithpoint :( nspoint) point;
+ (Nsvalue *) valuewithsize :( nssize) size;
+ (Nsvalue *) valuewithrect :( nsrect) rect;
-(Nspoint) pointvalue;
-(Nssize) sizevalue;
-(Nsrect) rectvalue;
Example:
Value = [nsvalue valuewithrect: rect];
[Array addobject: value];
...
Nsrect anotherrect = [value rectvalue];
Nsnull
Sometimes it is necessary to store a null value, and nil value cannot be stored in most objects. Therefore, nsnull can be used to solve this problem.
+ (Nsnull *) NULL;
Example:
[Contact setobject: [nsnull null]
Forkey: @ "home fax machine"];
So how to access and judge:
Id homefax;
Homefax = [contact objectforkey: @ "home fax machine"];
If (homefax = [nsnull null])
{
//... No fax machine
}