One. Exchange two methods.
Example 1:
static void Exchangedmethod (sel originalselector, sel Swizzledselector, class Class) {
Method Originalmethod = Class_ Getinstancemethod (class, originalselector);
Method Swizzledmethod = Class_getinstancemethod (class, swizzledselector);
BOOL Didaddmethod =
Class_addmethod (class,
originalselector,
method_getimplementation (Swizzledmethod ),
method_gettypeencoding (Swizzledmethod));
if (didaddmethod) {
Class_replacemethod (class,
swizzledselector,
method_getimplementation ( Originalmethod),
method_gettypeencoding (Originalmethod));
}
else {
method_exchangeimplementations (Originalmethod, Swizzledmethod);
}
}
+ (void) load {
static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
class = [self class];
Exchangedmethod (@selector (layoutsubviews), @selector (s_layoutsubviews), Class);
Exchangedmethod (@selector (hittest:withevent:), @selector (s_hittest:withevent:), Class);
Exchangedmethod (@selector (touchesbegan:withevent:), @selector (s_touchesbegan:withevent:), Class);
});
}
Example 2:
@implementation Uiviewcontroller (Tracking) + (void) load {static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{class = [self class];
SEL originalselector = @selector (viewwillappear:);
SEL swizzledselector = @selector (xxx_viewwillappear:);
Method Originalmethod = Class_getinstancemethod (class, Originalselector);
Method Swizzledmethod = Class_getinstancemethod (class, Swizzledselector);
If the swizzling is a class method, use the following method://Class class = Object_getclass ((id) self);
...//Method Originalmethod = Class_getclassmethod (class, Originalselector);
Method Swizzledmethod = Class_getclassmethod (class, Swizzledselector);
Exchange Implementation Method_exchangeimplementations (Originalmethod, Swizzledmethod);
});
} #pragma mark-method swizzling-(void) Xxx_viewwillappear: (BOOL) animated {[Self xxx_viewwillappear:animated];
NSLog (@ "viewwillappear:%@", self); }
Two. Add attributes to Category
The Objc_getassociatedobject method can take a variable of a class, even if the variable is a private variable. If the app uses a private variable, you can avoid the app being rejected by this method.
Nsobject+indiebandname.h
@interface nsobject (indiebandname)
@property (nonatomic, strong) NSString * Indiebandname;
@end
NSOBJECT+INDIEBANDNAME.M
#import "Nsobject+extension.h"
#import <objc/runtime.h>
static const void *indiebandnamekey = &IndieBandNameKey;
@implementation NSObject (indiebandname)
@dynamic indiebandname;
-(NSString *) indiebandname {
return objc_getassociatedobject (self, indiebandnamekey);
}
-(void) Setindiebandname: (NSString *) indiebandname{
objc_setassociatedobject (self, Indiebandnamekey, Indiebandname, objc_association_retain_nonatomic);
}
@end