iOS dynamic run-time methods

Source: Internet
Author: User

At some point, the program may need to determine the method to invoke based on the parameters obtained.

To implement such a function, you need to use the dynamic runtime method.

You first need to define the interface so that it can be called.

Then there is the dynamic invocation of the defined method.

Here are two ways to

The first type:

// with parameters, you need to add a colon Sel sel = nsselectorfromstring (@ "Save:"new];[ obj Performselector:sel withobject:@{@ "1":@ "One" }];

Using the first method, the program appears with a warning.

Second: (called using method Pointers)

MyObject obj = [MyObjectNew]; Sel sel= Nsselectorfromstring (@"Save:"); Imp imp=[obj Methodforselector:sel];/** ID Object * Method of SEL Object * parameter of ID method*/    void(*func) (ID, SEL,ID) = (void*) Imp;

Or you can write that.

((Void (*) (ID, SEL, id)) [obj Methodforslector:sel]) (obj, sel, @{@ "1": @ "one"}); Func (manager, SEL, @{@"1":@" One"});

In addition, the skilled use of ID types is very important.

NSString *param =@"{\"Mm\": \ "iosqiao\", \ "yhm\": \ "123456\"}"; IDobj =[nsjsonserialization jsonobjectwithdata:[param datausingencoding:nsutf8stringencoding] options:< /c2>0Error:nil]; MyObject*manager = [MyObjectNew]; if(!manager) {    return; } SEL sel= Nsselectorfromstring (@"Savestorage:"); IMP Imp=[manager Methodforselector:sel]; void(*func) (ID, SEL,ID) = (void*) Imp; Func (Manager, SEL, obj);

iOS dynamic run-time methods

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.