Struct is often used in C/C ++ development to help us encapsulate basic data types. In objective-C, struct can also be used to encapsulate data types. At the same time, cocoa touch also provides an nsvalue to help us better use struct in development.
We can use nsvalue to help us encapsulate some simple data structures. For example, we have defined a simple struct type.
Objective-C code
- Typedef struct {
- Int ID,
- Float height,
- Unsigned char flag
- } Myteststruct;
In this case, we can use the myteststruct struct to easily encapsulate data. For example
Objective-C code
- Myteststruct;
- Myteststruct. ID = 1;
- My teststruct. Height = 23.0;
- Myteststruct. Flag = 'a ';
- Nsvalue * value = [nsvalue valuewithbytes: & myteststruct objctype: @ encode (myteststruct)];
You can use the following method to retrieve the data in * value:
Objective-C code
- Myteststruct theteststruct;
- [Valeu getvalue: & theteststruct];
Then you can perform theteststruct operations to obtain the data.
For the nsvalue class, we can also use it when we display points or other geometric figures on the iPhone. For example, if we want to obtain the user's click track on the screen, we first think of using the cgpoint struct to save the data of each click. In this case, we can use + valuewithcgpoint in the nsvalue category to help us provide data for the CG framework.