A New Keyword @ dynamic is added to objective-C 2.0 to define dynamic attributes. Compared with @ synthesis, dynamic attributes are not automatically generated by the compiler, setter, or getter, but are dynamically added at runtime.
Generally, defining an attribute is similar to the following method:
@ Interface car: nsobject; @ property (retain) nsstring * Name; @ end @ implement car; @ synthesize name; @ end
In this case, the @ synthesize keyword tells the compiler to automatically implement setter and getter. In addition, if you do not use @ synthesize, you can also implement getter or setter by yourself.
@ Implement car; (nsstring *) name {return _ name;} (void) setname :( nsstring *) n {_ name = N ;}
Now, through @ dynamic, you can use the third method to implement the setter and getter of name. To implement dynamic attributes, you mustCodeOverwrite resolveinstancemethod to dynamically Add the setter and getter of the name. This method is called every time the method implementation cannot be found. In fact, the default Implementation of nsobject is to throw an exception.
Refer to the following code:
The following code defines dynamic attributes and implements dynamic attributes:
@ Interface car: nsobject @ property (retain) nsstring * Name; @ end --- car. M (void) dynamicsetname (ID self, Sel _ cmd, nsstring * n) {// This definition form is required. // Combined with the following type description character V, return void // @ indicates the first parameter ID //: sel // @ indicates the nnslog parameter (@ "the new name is going to send in: % @! ", N) ;}@ implement car @ dynamic name;-(bool) resolveinstancemethod :( SEL) SEL {nsstring * method = nsstringfromselector (SEL); If ([method is1_tostring: @ "setname:"]) {class_addmethod ([self class], Sel, (IMP) dynamicsetname, "V @: @"); // type description character, for more information, see the description of the @ encode keyword in the development documentation. Return YES:} return [Super resolveinstancemethod: sel] ;}@ end;
The above code dynamically implements the setter of name. Of course, if you want to call car. Name at this time, an error will be thrown because I have not implemented its getter.