Assigning values to model (inherited and NSObject objects) in a dictionary---------"IOS Development"

Source: Internet
Author: User

This tutorial describes the use of the runtime extension NSObject, can be directly in the dictionary to the model assignment, this is quite useful technology.

PS: Details about runtime will be introduced in detail later

Source:

Nsobject+property.h and NSOBJECT+PROPERTY.M

  nsobject+property.h//  modelvaluetest1.0////  Created by Lisa on 14-9-15.//  Copyright (c) 2014 Lisa. All rights reserved.//#import <Foundation/Foundation.h> @interface nsobject-(void) setdatadictionary :(nsdictionary *) datadictionary;-(nsdictionary*) datadictionary; @end

nsobject+property.m//modelvaluetest1.0////Created by Lisa on 14-9-15.//Copyright (c) 2014 Lisa. All rights reserved.//#import "Nsobject+property.h" #import <objc/runtime.h> @implementation NSObject #pragma mark--public method-(void) Setdatadictionary: (nsdictionary *) datadictionary{[self setattributes: Datadictionary obj:self];}    -(nsdictionary*) datadictionary{//Get the attribute list Nsarray *properties = [self propertynames:[self class]]; Gets the property value according to the property list return [self propertiesandvaluesdictionary:self properties:properties];}    #pragma mark---Private method//the Setter method by property name-(SEL) Getsetterselwithattibutename: (NSString *) attributename{    NSString *captial = [[AttributeName substringtoindex:1]uppercasestring];    NSString *setterselstr = [NSString stringwithformat:@ "set%@%@:", Captial,[attributename SubstringFromIndex:1]]; Return nsselectorfromstring (SETTERSELSTR);} Set properties by Dictionary-(void) SetAttributes: (nsdictionary *) Datadic obj: (ID) obj{//Get all key values Nsenumerator *keyenum = [Datadic keyenumerator];        The dictionary key value (corresponding to the model's attribute value one by one) id attrbutename = nil; while (attrbutename = [Keyenum Nextobject]) {//Get patchwork Setter method sel sel = [obj getsetterselwithattibutename:a                Ttrbutename];            Verifies if the setter method can respond to if ([obj Respondstoselector:sel]) {id value = nil;            ID tmpvalue = Datadic[attrbutename];                            if ([Tmpvalue Iskindofclass:[nsnull class]]) {//If it is a NSNull type, the value is empty value = nil;                            } else {value = Tmpvalue; }//Execute setter method [obj Performselectoronmainthread:sel withobject:value waituntildone:[nsthread ismain        Thread]]; }}//gets a list of property names for a class-(Nsarray *) PropertyNames: (Class) class{nsmutablearray *propertynames = [[Nsmutablearray Alloc]ini    T];    unsigned int propertycount = 0; objc_property_t *properties = Class_copypropertylist (class, &pRopertycount);        for (unsigned int i =0; i<propertycount; ++i) {objc_property_t property = Properties[i];        const char *name = Property_getname (property);    [PropertyNames addobject:[nsstring Stringwithutf8string:name];    } free (properties); return propertynames;}    Gets the value of this property based on an array of attributes-(nsdictionary*) Propertiesandvaluesdictionary: (ID) obj properties: (Nsarray *) properties{    Nsmutabledictionary *propertiesvaluedic = [Nsmutabledictionary dictionary];        For (NSString *property in properties) {SEL GetSel =nsselectorfromstring);            if ([obj Respondstoselector:getsel]) {nsmethodsignature *signature = nil;            Signature = [obj Methodsignatureforselector:getsel];            Nsinvocation *invocation = [Nsinvocation invocationwithmethodsignature:signature];            [Invocation settarget:obj];            [Invocation Setselector:getsel];            NSObject *__unsafe_unretained valueobj = nil;       [Invocation invoke];     [Invocation getreturnvalue:&valueobj];            Assign to @ "" string if (valueobj = = nil) {valueobj = @ "";        } Propertiesvaluedic[property] = Valueobj; }} return propertiesvaluedic;} @end

Model of the test

LModelItems.h and LMODELITEMS.M

  lmodelitems.h//  modelvaluetest1.0////  Created by Lisa on 14-9-15.//  Copyright (c) 2014 Lisa. All rights reserved.//#import <Foundation/Foundation.h> @interface lmodelitems:nsobject@property (nonatomic, Strong) NSString *name, @property (nonatomic,strong) NSNumber *age; @property (nonatomic,strong) nsdictionary * Addressdic, @property (nonatomic,strong) Nsarray *eventd; @end

  lmodelitems.m//  modelvaluetest1.0////  Created by Lisa on 14-9-15.//  Copyright (c) 2014 Lisa. All rights reserved.//#import "LModelItems.h" @implementation lmodelitems@end

Use the scene:

>>>>>lviewcontroller.h and LVIEWCONTROLLER.M in the controller

  lviewcontroller.h//  modelvaluetest1.0////  Created by Lisa on 14-9-15.//  Copyright (c) 2014 Lisa. All rights reserved.//#import <UIKit/UIKit.h> @interface lviewcontroller:uiviewcontroller@end

lviewcontroller.m//modelvaluetest1.0////Created by Itotem on 14-9-15.//Copyright (c) 2014 Lisa. All rights reserved.//#import "LViewController.h" #import "Nsobject+property.h" #import "LModelItems.h" @interface Lviewcontroller () @end @implementation lviewcontroller-(ID) initwithnibname: (NSString *) Nibnameornil Bundle: (    NSBundle *) nibbundleornil{self = [super Initwithnibname:nibnameornil Bundle:nibbundleornil]; if (self) {//Custom initialization} return to self;}    -(void) viewdidload{[Super Viewdidload];    Lmodelitems *model = [Lmodelitems new]; Assignment by Dictionary model.datadictionary = @{@ "name": @ "Lisa" @ "Age": @26,@ "addressdic": @{@ "Provinces": @ "Beijing" @ "area": @ "Haidian"},@ "Eventd": @[@ "First", @ "second", @ "third"]};
Print Assignment result NSLog (@ "%@", model.datadictionary); NSLog (@ "name=%@", model.name); NSLog (@ "age=%@", model.age); NSLog (@ "addressdic=%@", [Model.addressdic objectforkey:@ "Provinces"]); NSLog (@ "eventd=%@", MODEL.EVENTD); }-(void) didreceivememorywarning{[Super didreceivememorywarning]; Dispose of any resources the can be recreated.} @end

Printing information:

2014-09-15 17:11:36.948 modelvaluetest1.0[8386:60b] {

Addressdic = {

Area = "\u6d77\u6dc0\u533a";

Provinces = "\U5317\U4EAC";

};

Age = 26;

Eventd = (

First

Second

Third

);

name = Lisa;

}

2014-09-15 17:11:36.950 modelvaluetest1.0[8386:60b] Name=lisa

2014-09-15 17:11:36.951 modelvaluetest1.0[8386:60b] age=26

2014-09-15 17:11:36.952 modelvaluetest1.0[8386:60b] addressdic= Beijing

2014-09-15 17:11:36.952 modelvaluetest1.0[8386:60b] eventd= (

First

Second

Third

)

The following is a two-part core code (that meets a single function):

Assigning values to model (inherited and NSObject objects) in a dictionary---------"IOS Development"

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.