IOS: Objective-C (OC) Ideas and code examples for implementing automated description

Source: Internet
Author: User

IOS: Objective-C (OC) Ideas and code examples for implementing automated description
Keyword: the Objective-c oc description function automatically prints attributes and attribute values. The NSLog or po function is used to enumerate member variables during runtime. Xcode calls the description method of the object by default. If not, print the object address, which is inconvenient to view the object status. In particular, in RESTful programming, JSON objects returned by the server often have many attributes. If each object creates a class and implements the description method for these classes one by one, the heavy workload and repetitive work are not helpful to our coders, and some attributes are easy to be missed. Such repetitive work is more suitable for computers. The basic idea of implementing automatic description is that the base class implements this method, and the subclass only needs to define attributes as needed. The description algorithm of the base class is to read the class to which the object belongs during runtime (NOTE: When KVO is used, when there is an observer, the runtime will generate a new class for the observed class and return the type of the new class. For details, refer to the simple verification object of the author's iOS: KVO implementation principle and all member variables, then, KVC reads and writes the value of the member variable. BaseModel. m /////////////////////////////////////// /// //-(NSDictionary *) mapPropertiesToDictionary {// used to store the attribute (key) and its value (value) NSMutableDictionary * dictionary = [NSMutableDictionary dictionary]; // obtain the current Class Object Type class cls = [self Class]; // obtain the member variable list of the class object. The value of ivarsCount is uint ivarsCount = 0. Ivar * ivars = class_copyIvarList (cls, & ivarsCount); // traverses the member variable list, each variable is a const Iva struct of the Ivar type. R * ivarsEnd = ivars + ivarsCount; for (const Ivar * ivarsBegin = ivars; ivarsBegin <ivarsEnd; ivarsBegin ++) {Ivar const ivar = * ivarsBegin; // obtain the variable name NSString * key = [NSString stringwithuf8string: ivar_getName (ivar)];/* If the variable is declared as an attribute, the variable name is prefixed with an underscore '_', for example, @ property (nonatomic, copy) NSString * name; then key = _ name; To facilitate viewing attribute variables, in this special case, remove the underline prefix */if ([key hasPrefix: @ "_"]) key = [key substringFromIndex: 1]; // obtain the variable value id value = [Self valueForKey: key]; // If the processing property is not assigned a value, convert it to null. If it is nil, inserting will cause a program exception [dictionary setObject: value? Value: [NSNull null] forKey: key];} return dictionary;} The enumeration attribute is complete. The preceding Code does not process the parent class attribute because there are only two layers of classes in the business. If necessary, you can use the class_getSuperclass () method to enumerate the parent class member variables. When recursion is performed on the parent class, recursively export the class with the current enumeration to the root class NSObject, that is, cls = [NSObject class]. The rest is the description method for implementing the base class. BaseModel. m /////////////////////////////////////// /// //-(NSString *) description {NSMutableString * str = [NSMutableString string]; NSString * className = NSStringFromClass ([self class]); NSDictionary * dic = [self mapPropertiesToDictionary]; [dic dictionary: ^ (id key, id obj, BOOL * stop) {[str appendFormat: @ "% =%@\ n", key, obj] ;}]; return str ;} so far Can be basically completed. Subclass only needs to inherit the base class and declare the attribute in the. h file. User. m /////////////////////////////////////// /// // # import" baseModel. h "@ interface UserState: BaseModel @ property (nonatomic, copy) NSString * name; @ end although the function is implemented, there is still room for performance optimization in the previous implementation. MapPropertiesToDictionary must be called every time description is called for performance optimization. This is obviously unnecessary. Therefore, the optimization idea is to maintain a static hash table in the base class. For the first time that the subclass uses the description method, mapPropertiesToDictionary is called, and then the constructed attribute value dictionary is retrieved from the hash table. The following provides a reference implementation. BaseModel. m /////////////////////////////////////// /// ///static NSMutableDictionary * modelsDescription = nil; // initialize the hash table in the load or initialize method, which is a dictionary here. + (Void) load {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {modelsDescription = [NSMutableDictionary dictionary] ;}// modify description to construct a dictionary-(NSString *) description {//... if (value) {dic = (NSDictionary *) value;} else {dic = [self mapPropertiesToDictionary]; [modelsDescription setObject: dic forKey: className];} //...} next I will explain the differences between load and initialize OF THE ROOT NSObject class.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.