1. First, we need to know that this uses the runtime reflection mechanism.
So we need the header file runtime. h.
1-(bool) createtablebyclassattributes: (ID) classmodel {2 3 // obtain the class name when the table name, also for the reflection below, 4 nsstring * classname = nsstringfromclass ([classmodel class]); 5 6 // initialize a variable string 7 nsmutablestring * sqlquery = [nsmutablestring stringwithformat: @ "create table if not exists % @ (", classname]; 8 9 const char * cclassname = [classname utf8string]; 10 11 ID classm = objc_getclass (cclassname); 12 // I count, outcount put the number of our attributes 13 unsigned int outcount, i; 14 // The number of attributes obtained by reflection, 15 objc_property_t * properties = class_copypropertylist (classm, & outcount ); 16 17 // cyclically obtain the attribute name splicing database statement 18 for (I = 0; I <outcount; I ++) {19 objc_property_t property = properties [I]; 20 // obtain the attribute name 21 nsstring * attributename = [nsstring stringwithuf8string: property_getname (property)]; 22 23 if (I = outcount-1) {24 [sqlquery appendformat: @ "% @ text)", attributename]; 25 break; 26} 27 // Start splicing 28 [sqlquery appendformat: @ "% @ text,", attributename]; 29} 30 31 if ([self opendatabase] = Yes) {32 33 char * error; 34 int result = sqlite3_exec (_ dB, [sqlquery utf8string], null, null, & error); 35 if (result = sqlite_ OK) {36 return yes; 37} else {38 nslog (@ "% @", [self errorwithmessage: [nsstring stringwithformat: @ "% s", error]); 39 return no; 40} 41} else {42 nslog (@ "% @", [self errorwithmessage: @ "opendb failure"]); 43 return no; 44} 45}
// Of course, this is written in the database. You may need to import the libsqlite database and create a database to see its real effect.
PS: During the runtime, We can get all the attributes of a class, including the attribute name, value, type, and colleague, as well as the method name.
Here, the pure C language is used.
Here we will talk about reflection, mainly to give you a look at this idea.
The OC reflection mechanism obtains all the attributes of this class and creates a data table.