码迷,mamicode.com
首页 > 移动开发 > 详细

iOS Runtime-OC黑魔法

时间:2016-05-12 18:25:56      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:

 在项目中经常会发现一些奇怪的功能。不太能找的到代码的出处,但却实现了功能,很可能这是实用了运行时的东西。

运行时即Runtime 。使用起来很有意思。多了解也有助于对oc的理解。

这里我有写个关于Runtime 的demo     https://github.com/WangFeiF/WFRuntime


在这个博客里只是demo的摘要。详细可以下载demo。查看源码。

//
//  ViewController.m
//  Runtime
//
//  Created by 王飞 on 16/5/8.
//  Copyright © 2016年 com.wangfei. All rights reserved.
//

#import "ViewController.h"
#import <objc/runtime.h>
#import "WFPerson.h"
#import "UIImage+Swizzling.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageOrigin;
@property (weak, nonatomic) IBOutlet UIImageView *imageSwizzling;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self sendMessage];
    
    [self methodSwizzling];
}

- (void)sendMessage {
#pragma 消息机制
    Class classPerson  = objc_getClass("WFPerson");
    
    // 同过类创建实例对象
    // 如果这里报错,请将 Build Setting -> Enable Strict Checking of objc_msgSend Calls 改为 NO
    WFPerson *person = objc_msgSend(classPerson, @selector(alloc));
    
    person = objc_msgSend(person,@selector(init));
//    [person eat];
    
    objc_msgSend(person,@selector(runWithCount:),10);
    objc_msgSend(person, @selector(eat));
    
#pragma 动态关联方法
    /**
     *  person 对象并没有 sayHello 方法 这时候  用WFPerson 内部的hello 代替 sayHello
     */
    objc_msgSend(person, @selector(sayHello));

#pragma 消息转发
    /**
     *  person 发给stoke  的方法,通过黑魔法操作,转给了 touch
     */
    objc_msgSend(person, @selector(stoke));
}

#pragma 方法交换  详细操作  看UIImage+Swizzling的分类
- (void)methodSwizzling {
    UIImage *image = [UIImage imageNamed:@"hitLive"];
    _imageOrigin.image = image;
    
    NSLog(@"--------这是分界线---------");
    
    UIImage *imge = [UIImage tuc_imageNamedMethod:@"hitLive"];
    _imageSwizzling.image = imge;
}



@end

还有runtime 中的动态关联属性  可以查看博客:http://blog.csdn.net/qq_16844001/article/details/51122074




iOS Runtime-OC黑魔法

标签:

原文地址:http://blog.csdn.net/qq_16844001/article/details/51355175

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!