Just a little smile ^ ^

yoyo_zeng

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  112 随笔 :: 3 文章 :: 0 评论 :: 10万 阅读

When you send a message like [NSObject alloc] you are actually sending a message to the class object and that class object needs to be an instance of the MetaClass which itself is an instance of the root meta class

The basic implementation of a class in Objective-C looks like 

interface MyClass : NSObject {

//vars

NSInteger counter;

}

//methods

-voiddoFoo;

end

but the runtime has more than that to keep track of 

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

 

Objective-C Associated Objects
One thing recently introduced in Mac OS X 10.6 Snow Leopard was called Associated References. Objective-C has no support for dynamically adding on variables to objects unlike some other languages that have native support for this. So up until now you would have had to go to great lengths to build the infrastructure to pretend that you are adding a variable onto a class. Now in Mac OS X 10.6 the Objective-C Runtime has native support for this. If we wanted to add a variable to every class that already exists like say NSView we could do so like this... 

import < Cocoa/Cocoa.h> //Cocoa

include < objc/runtime.h> //objc runtime api’s

 

interface NSView CustomAdditions

propertyretain NSImage *customImage;

end

 

implementation NSView CustomAdditions

 

static char img_key; //has a unique address identifier

 

-NSImage *customImage

{

    return objc_getAssociatedObjectself&img_key;

}

 

-voidsetCustomImage:NSImage *image

{

    objc_setAssociatedObjectself&img_keyimage

                             OBJC_ASSOCIATION_RETAIN;

}

posted on   yoyo_zeng  阅读(144)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
点击右上角即可分享
微信分享提示