`
guafei
  • 浏览: 322693 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Runtime programming guide

阅读更多
objective-c有两个版本的runtime,“modern” 和 “legacy”,objective-c 2.0,iphone的应用和64位的OS X 10.5及以后的版本都使用的是modern版本的。
runtime系统是一个动态共享库,开放的接口都定义在/usr/include/objc.h文件中

objc_msgSend 方法:
在objective-c中,方法会在runtime的时候才进行绑定,而不是在编译阶段,编译器会在编译阶段,把方法编译成:[receiver message],然后再通过objc_msgSend(receiver, selector)来实现方法动态绑定,如果有参数,那么调用为objc_msgSend(receiver, selector, arg1, arg2, ...)

没一个类结构都包括两个比不可少的元素,指向父类的指针和类表,类表包含类的方法名、地址。一个类创建,内存会分配空间给类,然后初始化变量,其中isa变量是指向类结构的指针。继承自NSObject 或者 NSProxy的类都会有isa指针,一个NSObject对象内容和objc_object结构体内容相同。


objc_msgSend 绑定方法,isa指针先会去类的类表中寻找方法名和地址,如果没找到,就去父类的类表中寻找,直到NSObject类的类表。一个方法就这样的被动态的绑定给消息。为了加速绑定过程,runtime系统会cache常用方法。
objc_msgSend传入的两个参数,会返回self和_cmd
- strange {
      id  target = getTheReceiver();
      SEL method = getTheMethod();
      if ( target == self || method == _cmd )
          return nil;
      return [target performSelector:method];
  }

一个类定义一个方法,可以通过类指针methodForSelector:去指定方法的实现。methodForSelector是runtime的实现,不是OC的特性
void (*setter)(id, SEL, BOOL);
int i;
setter = (void (*)(id, SEL, BOOL))[target
    methodForSelector:@selector(setFilled:)];
for ( i = 0 ; i < 1000 ; i++ )
    setter(targetList[i], @selector(setFilled:), YES);

可以通过定义@dynamic,手动实现getter和setter方法,还可以通过resolveInstanceMethod:和 resolveClassMethod:来动态绑定对象方法和类方法。
void dynamicMethodIMP(id self, SEL _cmd) {
    // implementation ....
}

@implementation MyClass
  + (BOOL)resolveInstanceMethod:(SEL)aSEL
  {
      if (aSEL == @selector(resolveThisMethodDynamically)) {
            class_addMethod([self class], aSEL, (IMP) dynamicMethodIMP, "v@:");
            return YES;
}
      return [super resolveInstanceMethod:aSEL];
  }
@end

通过resolveInstanceMethod函数,来实现方法的转移。如果respondsToSelector: or instancesRespondToSelector:方法调用了,那么self会先去调用他们给定的方法。

一个OC的程序在running状态,可以加载新的类和类别,新的代码会加载到正在running的程序。动态加载可以做很多事情,比如不同的系统模块是被动态加载的。
虽然在objc/objc-load.h文件中定义了objc_loadModules动态加载模块,但是NSBundle类提供更方便的加载,详见NSBundle class reference

消息转移:
发送一个消息给对象,如果对象没有处理消息,那么会报错,但在报错之前,runtime系统会给对象第二次机会去处理消息。这个机会就是发送带有所有消息特征的NSInvocation对象参数,通过forwardInvocation:方法。 我们可以通过forwardInvocation方法来实现消息第一次没有处理的默认响应。
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
    if ([someOtherObject respondsToSelector:
            [anInvocation selector]])
        [anInvocation invokeWithTarget:someOtherObject];
    else
}
[super forwardInvocation:anInvocation];

forwardInvocation可以做的事情很多,可以让所有消息响应一个方法,或者不响应,或者实现对象属性方法的懒加载(初始化一个复杂对象,很多属性会在调用的时候初始化)等等,这个方法只有调用一个不存在的方法才会执行。可以通过查看NSInvocation class reference来查看。

if ( [aWarrior respondsToSelector:@selector(negotiate)] )
{  
   //the answer is NO, even though it can receive negotiate messages without error and respond to them, in a sense, by forwarding them to a Diplomat.
}

- (BOOL)respondsToSelector:(SEL)aSelector
{
    if ( [super respondsToSelector:aSelector] )
        return YES;
    else {
        /* Here, test whether the aSelector message can     *
         * be forwarded to another object and whether that  *
         * object can respond to it. Return YES if it can.  */
    }
return NO; }


声明变量:
@interface Lender : NSObject {
    float alone;
}
@property float alone;
@end

获取变量list
id LenderClass = objc_getClass("Lender");
  unsigned int outCount;
objc_property_t *properties = class_copyPropertyList(LenderClass, &outCount);
获取变量名称
const char *property_getName(objc_property_t property)
给定变量名称,获得其引用
objc_property_t class_getProperty(Class cls, const char *name)
objc_property_t protocol_getProperty(Protocol *proto, const char *name, BOOL
isRequiredProperty, BOOL isInstanceProperty)
获取变量name和值(值是encode过的)
const char *property_getAttributes(objc_property_t property)

打印所有的属性:
id LenderClass = objc_getClass("Lender");
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(LenderClass, &outCount);
for (i = 0; i < outCount; i++) {
    objc_property_t property = properties[i];
    fprintf(stdout, "%s %s\n", property_getName(property),
property_getAttributes(property));
}
  • 大小: 111.8 KB
  • 大小: 82.9 KB
分享到:
评论

相关推荐

    Objective-C 2.0 Runtime Programming Guide

    Objective-C 2.0 Runtime Programming Guide

    Objective-C Runtime Programming Guide

    The Objective-C language defers as many decisions as it can from compile time and link time to runtime. Whenever possible, it does things dynamically. This means that the language requires not just a ...

    objective c runtime programming guide

    关于objective c在运行时会出现的问题等,纯英文版

    Objective-C Runtime Programming Guide中文版

    Objective-C 语言将决定尽可能的从编译和链接时推迟到运行时。只要有可能,Objective-C 总是使用动态 的方式来解决问题。这意味着 Objective-C 语言不仅需要一个编译器,同时也需要一个运行时系统来执行 编译好的...

    The Objective-C Programming Language

    This document is about the first component of the development environment—the programming language.... The runtime environment is described in a separate document, Objective-C Runtime Programming Guide.

    OpenCL Programming Guide - A. Munshi, et al

    Programming with OpenCL C and the runtime API Using buffers, sub-buffers, images, samplers, and events Sharing and synchronizing data with OpenGL and Microsoft’s Direct3D Simplifying development ...

    iOS Application Programming Guide

    Understanding the iOS Runtime Environment 10 Designing the Core of Your Application 10 Supporting Common Application Behaviors 10 Executing Code in the Background 10 Meeting the App Store and System ...

    Objective-C Programming: The Big Nerd Ranch Guide (2nd Edition)

    Objective-C Programming: The Big Nerd Ranch Guide (2nd Edition).epub (epub 格式) Want to write iOS apps or desktop Mac applications? This introduction to programming and the Objective-C language is ...

    Embedded Programming with Android: Bringing Up an Android System from Scratch

    The First Practical, Hands-On Guide to Embedded System Programming for Android Today, embedded systems programming is a more valuable discipline than ever, driven by fast-growing, new fields such ...

    The Go Programming Language Phrasebook

    This guide gives you the code "phrases" you need to quickly and effectively complete a wide variety of projects with Go, today's most exciting new programming language. Tested, easy-to-adapt code ...

    Programming Elixir

    You’re also investigating designs that help you maximize uptime and manage security., This book is your guide to Elixir, a modern, functional, and concurrent programming language. Because Elixir ...

    Hands-On Network Programming with C# and .NET Core.epub

    Hands-On Network Programming with C# and .NET Core: A comprehensive guide to understanding network architecture, communication protocols, and network analysis to build secure applications compatible ...

    JavaScript Functional Programming for JavaScript Developers (PDF, EPUB, MOBI)

    The first module Mastering JavaScript, stress on practical aspects of Javascript development like—Functions and Closures, Runtime debugging techniques, project layout, events and DOM processing, ...

    The C# Programmer's Study Guide (MCSD): Exam: 70-483

    "The C# Programmer’s Study Guide (MCSD): Exam: 70-483" English | ISBN: 1484228596 | 2017 | 475 pages | PDF | 5 MB Prepare for Microsoft Certification Exam 70-483: Programming in C#. The “What, Why...

    Java 9 Programming By Example

    You will be able to use the Java runtime tools, understand the Java environment, and create Java programs. We then cover more simple examples to build your foundation before diving to some complex ...

    The C# Programmer’s Study Guide (MCSD)--2017

    Asynchronous programming with the Async and Await keywords to maximize performance of slow applications Regular expressions to validate user input Reflection to create and handle types at runtime ...

    Tomcat.6.Developer's.Guide

    a Tomcat installation, configuring the runtime environment, and on deploying web applications. On the other hand, while books on servlet programming are targeted at Java web developers, they often ...

Global site tag (gtag.js) - Google Analytics