iOS calls private methods

Source: Internet
Author: User

Sometimes there is a scenario in the code that calls for a private method, such as not wanting to import too many files, designing some decoupled modules, and looking at the code that is not exposed in others ' modules for analysis.

There are many ways to call private methods in iOS, mainly through runtime. Let's test it myself.

Create a new person class that does not write code in Person.h, as in PERSON.M:

#import " Person.h " @implementation person-(void) eat{    NSLog (@ "xxx eat====");} -(void) Eat: (NSString *) str str2: (NSString *) str2 STR3: (NSString *) str3{    NSLog (@ "  xxx eat====%@==%@==%@", str, str2, STR3);} @end

"Find the method in this class of methodlists."

To invoke a private method, you first need to know what the class has. You can get some information about the method by using the following code: (whether private or public, as long as it is in the methodlists of the Class)

//Get instance Method- (void) getmethods{intOutcount =0; person*p = [PersonNew]; Method*methods = Class_copymethodlist ([pclass], &outcount);  for(inti =0; i < Outcount; i + +) {NSLog (@"=============%d", i); //Get method NameMethod method =Methods[i]; SEL MethodName=Method_getname (method); NSLog (@"Method name =%@", Nsstringfromselector (methodName)); //Get Parameters        Chararginfo[ +] = {}; unsignedintArgcount =method_getnumberofarguments (method);  for(intj =0; J < Argcount; J + +) {            //parameter TypeMethod_getargumenttype (method, J, Arginfo, +); NSLog (@"parameter type =%s", Arginfo); memset (Arginfo,' /', strlen (Arginfo)); }                //Gets the method return value type        Charrettype[ +] = {}; Method_getreturntype (method, RetType, +); NSLog (@"return type value type =%s", RetType); } free (methods);}

The code above uses runtime to get information about methods: The method name, the type of the parameter, and the return value type. The above method prints the result as follows:

=============0 method name = Eat parameter type = @ parameter Type = : return type value type = v============= 1 method Name = eat:str2:str3: parameter type = @ parameter type = : parameter type = @ parameter type = @ parameter type = @ return type value type = V

The type of printing is some symbol, do not know what the ghost is, but actually this is the type of apple encoding. The meaning of this comparison is as follows:

V    A void  --(empty) @    Object (whether statically typed or typed ID)--(ID type) :    A Method Selector (SEL)-(method name)

The method information printed above also has two parameters in the Eat method, and there are two hidden parameters for each method. (_cmd is the current method number)

"Call Private Method"

There are several ways to call a private method, but in the end it is very similar. As follows:

1. Use Performselector below the 2 and 3 line results. This is better than using the object direct invocation benefit is that the compiler will not error or expose the header file without a method.

1 New ]; 2  xxx eat====
3 [P performselector:nsselectorfromstring (@ "eat")]; Log:xxx eat====

2. Using Objc_msgsend, comparing the above objc_msgsend benefits is more convenient when passing multiple parameters. Objc_msgsend in-depth learning

New@"1"@ "2"@ "3 "); Log:eat====1==2==3

3. Using the function to realize the IMP,IMP type structure is the same type as the Objc_msgsend, and no difference is achieved in 2

New= [P methodforselector: @selector (Eat)]; void (* tempfunc) (ID target, SEL) = (void *//  log:xxx eat====

4. Use the class object to send a message, the above 3 methods need to refer to the Person.h header file, where the class object is called to solve the problem.

Class pclassobj = nsclassfromstring (@ "person"new], @selector ( Eat));

"Class Object"

Enter objc.h to view the Class and Object structure definitions. Each objc_object has an Isa pointer pointing to the Objc_class to which this object belongs.

/// An opaque type, represents an Objective-c class. struct objc_class *class; /// represents an instance of a class. struct objc_object {    Class _nonnull Isa  objc_isa_availability;};

Look again at the structure defined by Objc_class.

structObjc_class {class _nonnull Isa objc_isa_availability;#if!__objc2__Class _nullable Super_class objc2_unavailable; Const Char*_nonnull name objc2_unavailable; Longversion objc2_unavailable; Longinfo objc2_unavailable; Longinstance_size objc2_unavailable; structObjc_ivar_list *_nullable Ivars objc2_unavailable; structObjc_method_list * _nullable *_nullable methodlists objc2_unavailable; structObjc_cache *_nonnull Cache objc2_unavailable; structObjc_protocol_list *_nullable protocols objc2_unavailable;#endif} objc2_unavailable;

The ISA in it points to the metaclass (Meta Class). Class and Metaclass:

    • When we send a message to an instance (the method that begins), it is found in the methodlists of the corresponding class of the instance.
    • When we send a message to a class (the method that begins with the +), it is found in the Metaclass methodlists of the class.

  

    • Each Class has an Isa pointer pointing to a unique Meta Class
    • Each meta class Isa pointer points to the topmost meta class, NSObject's Metaclass, while the top Metaclass's Isa pointer points to itself

iOS calls private 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.