IOS runtime you know, you gotta use it.

Source: Internet
Author: User

Say humorous digression:

I have just come to this company, the boss let me download a tenderness, go up to find their peers, more know some peers. In fact the original intention of the good, but recently these two days I unloaded it, not for others, too much negative energy! This line of iOS has not been booming since 2016, and in this line of work, these are sure to know. But is not the bird overwhelming how long did not find a job, full street is the IOS program ape these topics. See also give me no role, the only thing you can do is quietly do what you should do. Myself into iOS this line also 1.5, except the training of the months, the real work also more than a year, and sometimes think, actually did not feel how bad, how do not know, but at least now, you have a job, have mouth food, there is time for you to learn, what is not satisfied? In my own shallow consciousness, programming ideas are the same, like iOS you might also like Android, java,js,php and so on. Live to the old, learn the old, that constantly to learn the heart is their greatest reliance.

Back to the point:

Before you know the runtime, do not remember a few months ago, and recently encountered this problem, or summarize it, summed up the bad place, forgive me.

Runtime commonly known as "Runtime", the project has a compilation and run two states, this should be understood. is a set of underlying C-language APIs. OC is a dynamic language, some things will not be placed on our compile time to deal with, will wait until the runtime to deal with. The following is said, we recommend that you follow the table of this project, import the following header file point we will discuss it slowly!

#import <objc/runtime.h>

Look at the top of him:

An opaque type the represents a method in a class definition.typedef struct Objc_method *method;  Method///An opaque type, represents an instance variable.typedef struct Objc_ivar *ivar;   Variable///opaque type that represents a category.typedef struct objc_category *category;  Categories are also called classifications///opaque type that represents an objective-c declared property.typedef struct Objc_property *objc_property_t ; Property

definition in the comments in the code above we said, and then look down you see is the expression of the class:

struct Objc_class {    class Isa  objc_isa_availability; #if!__objc2__    class Super_class                                        objc2_ Unavailable;    const char *name                                         objc2_unavailable;    Long version                                             objc2_unavailable;    Long info                                                objc2_unavailable;    Long instance_size                                       objc2_unavailable;    struct objc_ivar_list *ivars                             objc2_unavailable;    struct objc_method_list **methodlists                    objc2_unavailable;    struct Objc_cache *cache                                 objc2_unavailable;    struct objc_protocol_list *protocols                     objc2_unavailable; #endif} objc2_unavailable;/* use ' Class ' instead of ' struct Objc_class * ' * *

Class Super_class points to the parent class.

The const char *name class has the name of the version of the long version class, and the initialization defaults to 0, and the following functions Class_setversion and class_getversion can be modified and read

Long info ID.

The size of the instance variable of the long Instance_size class, including the inherited parent class.

The address of the struct objc_ivar_list *ivars member variable.

struct Objc_method_list **methodlists

struct Objc_cache *cache A pointer to the most recently used method struct Objc_protocol_list *protocols the protocol that follows.

Here is a series of methods, here to summarize the common, in the following code comments will say the more detailed points:

#import "ViewController.h" #import <objc/runtime.h>/** * Define a protocol for the test */@protocol protocoltestdelegate <nsobject > @optional-(void) protocoltestdelegate; @end @interface Viewcontroller ()/** * Defines the properties of three Tests */@property (nonatomic, Strong) NSString * TESTSTRING1; @property (nonatomic,strong) nsstring * TESTSTRING2; @property (Nonatomic,strong)    NSString * TESTSTRING3; @end @implementation viewcontroller-(void) viewdidload {[Super viewdidload];    /** * Define member variables for three Tests */NSString * stringone;    NSString * STRINGTWO; NSString * STRINGTHREE;
unsigned int count; Objc_export objc_property_t *class_copypropertylist (class cls, unsigned int *outcount)//Below is an official comment, presumably translated;/** Describes the property list of a class * describes the properties declared by a class. * * @param CLS The class want to inspect. Parameter Outcount This parameter returns the length of your array of this attribute list * @param outcount on return, contains the length of the returned array. * If \e Outcount is \c NULL, the length was not returned. * This method returns a list of properties for the array * @return an array of pointers of type \c objc_property_t describing the properties * Declared by the class. Any properties declared by Superclasses is not included. The returned array contains the Outcount pointer with null endings, which must be freed with free () * The array contains \c *outcount pointers followed by a \c NULL term Inator. You must free the array with \c free (). * * If \e CLS declares no properties, or \e cls is \c Nil, returns \c NULL and \c *outcount is \c 0. *////Here is &count, is the address of Count, Outcountis a pointer to the length of the returned array, the value is passed to the address of the variable, and the system returns the length to the variable//attribute objc_property_t * propertylist = class_copypropertylist ([Self class],& Amp;count); for (unsigned int i = 0; i<count; i++) {//objc_property_t property//(nonnull const char *) const char * property = Property_getname (Propertylist[i]); NSLog (@ "Property%@", [NSString Stringwithutf8string:property]); }/** * Print 2016-08-29 11:37:03.302 runtimetest[10078:132260] Property testString1 2016-08-29 11:37:03.303 Runtimetest[10078:132260] Property testString2 2016-08-29 11:37:03.303 runtimetest[10078:132260] Property Teststrin G3 *//method * Methontlist = Class_copymethodlist ([self class], &count); for (unsigned int i = 0; i<count; i++) {Method methond = methontlist[i]; NSLog (@ "Methond%@", Nsstringfromselector (Method_getname (Methond))); }/** * 2016-08-29 14:01:30.458 runtimetest[16581:201546] MeThond classtestone 2016-08-29 14:01:30.458 runtimetest[16581:201546] Methond classtesttwo 2016-08-29 14:01:30.45 9 runtimetest[16581:201546] Methond classtesthree 2016-08-29 14:01:30.459 runtimetest[16581:201546] Methond TestStri NG1//TestString1 Get method 2016-08-29 14:01:30.459 runtimetest[16581:201546] Methond setteststring1:2016-08-29 14 : 01:30.459 runtimetest[16581:201546] methond testString2 2016-08-29 14:01:30.459 runtimetest[16581:201546] Methond s etteststring2:2016-08-29 14:01:30.459 runtimetest[16581:201546] methond testString3 2016-08-29 14:01:30.459 RunT imetest[16581:201546] Methond setteststring3:2016-08-29 14:01:30.459 runtimetest[16581:201546] Methond. Cxx_destruc T//2016-08-29 14:01:30.459 runtimetest[16581:201546] methond didreceivememorywarning 2016-08-29 14:01:30.460 Ru NTIMETEST[16581:201546] Methond Viewdidload *//member Variable Ivar * ivarlist = Class_copyivarlist ([self class], &co UNT); for (unsigned INT i = 0; i<count; i++) {Ivar Ivar = ivarlist[i]; const char *ivarname = Ivar_getname (Ivar); NSLog (@ "Ivar%@", [NSString Stringwithutf8string:ivarname]); }/** * 2016-08-29 14:12:17.750 runtimetest[17233:209405] Ivar _teststring1 2016-08-29 14:12:17.751 Run TIMETEST[17233:209405] Ivar _teststring2 2016-08-29 14:12:17.751 runtimetest[17233:209405] Ivar _testString3 * /__unsafe_unretained Protocol **protocollistm = Class_copyprotocollist ([self class], &count); for (unsigned int i =0; i<count; i++) {Protocol * myprotocal = protocollistm[i]; const char * protocalname = Property_getname ((__bridge objc_property_t) (myprotocal)); NSLog (@ "Protocal%@", [NSString Stringwithutf8string:protocalname]); }//Do any additional setup after loading the view, typically from a nib.} /** * Defines a method of three Tests */-(void) classtestone{NSLog (@ "I am the Viewcontroller methond");} -(void) Classtesttwo{}-(void) classtesthree{}-(void) didreceivememorywarning {[Super didreceivememorywarning]; Dispose of any resources the can be recreated.} @end

There are many more:

In fact, this piece is just a lot of, like method Exchange, dynamic Add method, interception calls and so on, but this can not be disorderly blowing, I have no use of the project, the future may use it, now has a navigation bar gradient such effect, the code out!

Add a category to Uinavigationbar:

#import <objc/runtime.h> #import "Uinavigationbar+background.h" @implementation Uinavigationbar (Background)// Add dynamic properties to Uinavigationbar static char backgroundkey;-(UIView *) backgroundview{return objc_getassociatedobject (self, & Amp;overlaykey);} -(void) Setoverlay: (UIView *) backgroundview{objc_setassociatedobject (self, &backgroundkey, Backgroundview, OBJC _association_retain_nonatomic);} -(void) Nasetbackgroundcolor: (Uicolor *) backgroundcolor{if (!self.        Backgroundview) {[self setbackgroundimage:[uiimage new] forbarmetrics:uibarmetricsdefault]; Self. Backgroundview = [[UIView alloc] Initwithframe:cgrectmake (0, -20, [UIScreen mainscreen].bounds.size.width, Cgrectgetheight (self.bounds) + 20)]; 20 higher than navigation, obscuring the status bar self.        backgroundview.userinteractionenabled = NO; Self. Backgroundview.autoresizingmask = uiviewautoresizingflexiblewidth|        Uiviewautoresizingflexibleheight; Adds a run-time property to the navigation. UIView Type: Place on top of navigation [self Insertsubview:selF. Backgroundview atindex:0]; }
Self. Backgroundview.backgroundcolor = BackgroundColor;}
-(void) cnreset{[self setbackgroundimage:nil forbarmetrics:uibarmetricsdefault]; [Self. Backgroundview Removefromsuperview]; Self. Backgroundview = nil; }
@end

Then in the proxy method of the Uiscrollviewdelegate:

-(void) Scrollviewdidscroll: (Uiscrollview *) ScrollView {//essence is to let the navigation bar add the Backgroundview property to change the color according to your scrollView sliding range [ Self.navigationController.navigationBar Nasetbackgroundcolor:[color Colorwithalphacomponent:alpha];  }

This is an effect that is seen on the web, which is the gradient of this navigation bar:

IOS runtime you know, you gotta use it.

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.