ios_21 Buy _ "Run-time" converts a dictionary into an object model

Source: Internet
Author: User

Eventually:



Core code:

Nsobject+dict.h

  nsobject+dict.h//  Handsome _ buy////  Created by Beyond on 14-8-14.//  Copyright (c) 2014 Com.beyond. All rights reserved.//  uses the runtime to turn Dict into objects #import <Foundation/Foundation.h> @interface nsobject (Dict)//an object, Call this method, the parameter passes a dictionary, then, through the runtime, the dictionary all the value of V, can be assigned to the object corresponding to the member property above-(void) Setvalueswithdict: (Nsdictionary *) dict; @end
NSOBJECT+DICT.M
nsobject+dict.m//Handsome _ buy////Created by Beyond on 14-8-14.//Copyright (c) 2014 Com.beyond. All rights reserved.//#import "nsobject+dict.h"//runtime required #import <objc/message.h> #import <objc/runtime.h>@ Implementation NSObject (DICT)//An object, call this method, parameters pass a dictionary, you can automatically pass all the values in the dictionary to the object corresponding to the member property (void) through the run time.        :(nsdictionary *) dict{//class name of this class class C = [self class];        while (c) {//1. Obtain all member variables of this class unsigned int outcount = 0;                Ivar *ivars = Class_copyivarlist (c, &outcount);                        for (int i = 0; i<outcount; i++) {Ivar Ivar = ivars[i];                        2. Attribute name nsmutablestring *name = [nsmutablestring stringwithutf8string:ivar_getname (Ivar)];                        Delete the first _ [name Replacecharactersinrange:nsmakerange (0, 1) withstring:@ ""];            3. Remove the attribute value nsstring *key = name; if ([Key isequaltostring:@ "desc"]) {key = @ "DescriptIon ";            } if ([Key isequaltostring:@ "id"]) {key = @ "id";            }//Remove the corresponding value ID in the parameter dictionary value = Dict[key];                        Robustness judgment, if the dictionary does not have the value corresponding to this key, then go to the next time for loop if (!value) continue;            4. Construct SEL//First letter NSString *cap = [name substringtoindex:1];            Initial capitalization cap = cap.uppercasestring;            Replace capital letters with the original initials [name Replacecharactersinrange:nsmakerange (0, 1) withstring:cap];            Stitching set [name insertstring:@ "set" atindex:0];            Stitching Colon: [Name appendstring:@ ":"];                        SEL selector = nsselectorfromstring (name);                        5. Attribute type, if it is a basic type, to be converted to an object nsstring *type = [NSString stringwithutf8string:ivar_gettypeencoding (Ivar)]; if ([Type hasprefix:@ "@"]) {//If the object type, send the message directly objc_msgsend (self, selector, Val            UE);               } else { If it is a non-object type, that is, the base object type, you want to go to the object type if ([Type isequaltostring:@ "D"]) {objc_msgsend (self, Selec                Tor, [value doublevalue]);                } else if ([Type isequaltostring:@ "F"]) {objc_msgsend (self, selector, [value floatvalue]);                } else if ([Type isequaltostring:@ "I"]) {objc_msgsend (self, selector, [value intvalue]);                } else {objc_msgsend (self, selector, [value longlongvalue]);    }}}//For loop has traversed all the members of this class, get its parent class to continue the above operation until its parent class is empty C = Class_getsuperclass (c);  }} @end/* Class_getsuperclass Returns The superclass of a class. Class Class_getsuperclass (class CLS) Parameters CLS A class object.  Return Value The superclass of the class, or nil if CLS is a root class, or nil if CLS is nil.  Discussion should usually use NSObject ' s superclass method instead of this function. Availability Available in IOS 2.0 and later. Declared in OBjc/runtime.h * * 


Cities.plist file to object model:



A set of corresponding models SECTION.M

citysectionbyletter.m//Handsome _ buy////Created by Beyond on 14-8-14.//Copyright (c) 2014 Com.beyond. All rights reserved.//data model, a group section, member 1: Group name, such as Group B member 2: is an array, cities, loaded with Group B this group all the cities below, each member of the array is a City object #import " Section.h "//City model #import" City.h "@implementation section//key! The value of cities in the dictionary is also a dictionary array, and we need an array of cities objects, so to intercept the Setcities method , the dictionary array, the traversal, the object is added to an array, and then the object array is assigned to the member property cities-(void) Setcities: (Nsmutablearray *) cities{//Intercept "runtime" The value of the key--cities in the Dictionary: The Dictionary array is assigned to the member cities, but should be converted to a number of objects, and then assigned to the member properties//When the cities is empty or the inside is already an object model, you can directly assign the value, instead of calling the classification method to turn the dictionary    The object model has the id obj = [cities lastobject]; if (![        obj Iskindofclass:[nsdictionary class]]) {_cities = cities;    Return    } nsmutablearray *cityarr = [Nsmutablearray array];        For (Nsdictionary *dict in cities) {City *city = [[City alloc] init];        Call the run-time method in the taxonomy to convert the k-v in the dictionary to an object [city Setvalueswithdict:dict];    [Cityarr addobject:city]; }//Finally, assign an array of objects to the member property cities array _cities = CITyarr;} @end

a city-corresponding model

  city.m//  Handsome _ buy////  Created by Beyond on 14-8-14.//  Copyright (c) 2014 Com.beyond. All rights reserved.//  data Model, a city, member 1: The name of the town, such as Beijing  member 2: is an array, districts, with all the boroughs of the city under Beijing, each member of the array is a district object #import "City.h"//Data Model #import "District.h" @implementation city//key! The value of districts in the dictionary is also a dictionary array, and we need an array of District objects, So to intercept the Setdistricts method, the dictionary array, the traversal, the object is added to an array, and then the object array is assigned to the member property districts-(void) Setdistricts: (Nsmutablearray *) districts{    //Intercept "runtime" key--cities the value in the dictionary: The Dictionary array is assigned to the member cities and should be transferred to the object, and then assigned to the member property    Nsmutablearray * Districtarr = [Nsmutablearray array];    For (Nsdictionary *dict in districts) {        District *district = [[District alloc] init];        Call the run-time method in the taxonomy to convert the k-v in the dictionary to an object        [district setvalueswithdict:dict];        [Districtarr addobject:district];    }    Finally, an array of objects is assigned to the member property Districts array    _districts = Districtarr;} @end

CITYLOCATIONCONTROLLER.M

citylocationcontroller.m//Handsome _ buy////Created by Beyond on 14-8-14.//Copyright (c) 2014 Com.beyond. All rights reserved.//Click the bottom 2nd position button below the dock, pop up the city selection controller with PopOver packaging, above is a search box, below is a tableview (according to the city's pinyin group) #import " CityLocationController.h "//Mask #import" CoverOnTableView.h "//Meta Data tool #import" MetaDataTool.h "//Data Model---grouping #import" Section.h "//Data Model---City #import" City.h "//Data Model---Administrative Region #import" District.h "//above Searchbar height # define Ksearchbarh 44@ Interface Citylocationcontroller () <uitableviewdatasource, uitableviewdelegate, uisearchbardelegate>{// The array loaded from plist, a total of 23 members, each member is a dictionary, each dictionary has two to kv, a pair is name-->a, the other pair is cities---> Array (the members of the array are dictionaries, a dictionary corresponds to a city, the dictionary has three pairs of kv, respectively: Name---> BEIJING, hot---->1,districts---> Array (the array corresponds to a dictionary, representing a region, with two pairs of kv in the dictionary: name---> Chaoyang District, Neighbours--->    Array (the member of the array is string ...)) Nsmutablearray *_sections;    All City Group information//view above is Uisearchbar, below is UITableView uisearchbar *_searchbar;    UITableView *_tableview;      UITableView above a layer of masks, covering Coverontableview *_cover; //Tgsearchresultcontroller *_searchresult;}        @end @implementation citylocationcontroller-(void) viewdidload{[Super Viewdidload];        1. Add the search box above Uisearchbar [self addsearchbar];        2. Add the tableview below [self addtableview];    3. Using the tool class, load the city array data [self loadcitiesmetadata];    }//1. Add search box uisearchbar-(void) addsearchbar{_searchbar = [[Uisearchbar alloc] init];    _searchbar.autoresizingmask = Uiviewautoresizingflexiblewidth;    _searchbar.frame = CGRectMake (0, 0, self.view.frame.size.width, Ksearchbarh);    Monitor Searchbar gain focus, lose focus, character changes and other events _searchbar.delegate = self;    _searchbar.placeholder = @ "Please enter city name or pinyin"; Search.tintcolor gradient//Search.barstyle style [Self.view Addsubview:_searchbar];}    2. Add the lower tableview-(void) addtableview{_tableview = [[UITableView alloc] init];    CGFloat TABLEVIEWH = Self.view.frame.size.height-ksearchbarh;    _tableview.frame = CGRectMake (0, Ksearchbarh, Self.view.frame.size.width, TABLEVIEWH); _tableview.dataSource = self;    _tableview.delegate = self; Important ~ Because this controller is inside the PopOver controller, PopOver also set the content size only, 480 _tableview.autoresizingmask = Uiviewautoresizingflexiblewidth |    Uiviewautoresizingflexibleheight; [Self.view Addsubview:_tableview];} 3. Using the tool class, load the city array data-(void) loadcitiesmetadata{//The array loaded from plist, a total of 23 members, each member is a dictionary, each dictionary has two to kv, the pair is Name-->a, The other pair is cities---> Array (the members in the array are dictionaries, a dictionary corresponds to a city, and the dictionary has three pairs of kv, respectively: Name---> Beijing, hot---->1,districts---> Arrays (    The array corresponds to a dictionary, representing a district, with two pairs of kv in the dictionary: name---> Chaoyang District, Neighbours---> Array (members of the array are string ...))    _sections = [Nsmutablearray array];    Nsarray *sections = [Metadatatool sharedmetadatatool].allsections; Assigns the section array returned by the tool class to the member variable for use by the TableView data source [_sections addobjectsfromarray:sections];} #pragma mark-Data source method #pragma mark-Data source method//Total number of groupings (23 alphabetic groups)-(Nsinteger) Numberofsectionsintableview: (UITableView *) tableview{return _sections.count;} Number of rows per group (number of cities)-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) section{//Group Section *s = _sections[section]; The number of city arrays in the first group return S.cities.count;} Cell-unique content for each row-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *)    indexpath{static NSString *cellidentifier = @ "Citylistcell";        UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:cellidentifier]; if (cell = = nil) {cell = [[UITableViewCell alloc] Initwithstyle:uitableviewcellstyledefault reuseidentifier:cellid    Entifier];    }//Group section *s = _sections[indexpath.section];    The first few lines (cities) City *city = S.cities[indexpath.row];    City name cell.textLabel.text = City.name; return cell;}    Each group of headertitle-(NSString *) TableView: (UITableView *) TableView titleforheaderinsection: (nsinteger) section{//Group    Section *s = _sections[section]; Group name, such as ABCD return s.name;} Grouped index title to the right of the table-(Nsarray *) Sectionindextitlesfortableview: (UITableView *) tableview{//Important ~ Remove the value of the key name for each group in the _sections array (such as ABCD ...), andPut all of these values into a new array, and the new array returned is the title of the grouped index return [_sections valueforkeypath:@ "name"];} #pragma mark-Search box proxy method//Search box start editing (start focusing, get focus)-(void) searchbartextdidbeginediting: (Uisearchbar *) searchbar{//1. Animation effect, display        The Cancel button on its right [Searchbar setshowscancelbutton:yes Animated:yes]; 2. The animation shows the masking (mask), and internally binds a, tap gesture listener if (_cover = = nil) {_cover = [Coverontableview coverwithtarget:self action:@    Selector (Coverclick)];    }//3. Cover must be fully covered on tableView _cover.frame = _tableview.frame;    [Self.view Addsubview:_cover];    4. Start full transparent (invisible) _cover.alpha = 0.0;    [UIView animatewithduration:0.3 animations:^{//Let cover turn black [_cover alphareset]; }];}        Monitor cover is tap, remove cover, hide Cancel button, exit keyboard-(void) coverclick{//1. After the animation is complete, remove the cloak [UIView animatewithduration:0.3 animations:^{    _cover.alpha = 0.0;    } completion:^ (BOOL finished) {[_cover Removefromsuperview];    }];        2. Hide _searchbar the rightmost cancel button [_searchbar setshowscancelbutton:no animated:yes]; 3. Let _searChbar Cancel the first responder, that is, exit the keyboard [_searchbar Resignfirstresponder]; [Self.view Endediting:yes];} When the search box is clicked on the keyboard above the cancel key (i.e. _searchbar loses focus)-(void) searchbartextdidendediting: (Uisearchbar *) searchbar{[self Coverclick] ;} When you click the Cancel button on the right side of the search box-(void) searchbarcancelbuttonclicked: (Uisearchbar *) searchbar{[self coverclick];} @end









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.