为什么category不能添加实例变量

2017-05-23  本文已影响0人  百思不得Ting姐

来自stackoverflow的答案,作者说只是猜想,也可能猜错了,不过我觉得很有道理。

不想看英语,请到最后看大概意思

Think of the Objective-C's ivars like a plain old C-structure. When you instantiate an instance of a class, a block of memory is created large enough to hold that structure.

Let's say you have an NSString. Lots and lots of existing code is compiled to use NSString. Lots of this code is built into libraries and frameworks. That compiled code was created knowing that the ivars of NSString take X number of bytes and are at some given offsets within that memory.

Now in your own little project lets say you create a category on NSString and want to add an ivar. In theory, any code in your project that includes the header file for the category would know that the size of this "new"NSString(plus category) takes X + Y bytes. This is much like a subclass. This newly compiled code could properly deal with the additional ivar(s).

But all of the pre-compiled code, the libraries and frameworks, would have no knowledge of the additional ivars. When NSString instances are created there, the memory is only X bytes, not X + Y bytes. Chaos ensues as your app code gets a reference to that smaller chunk of memory and tries to access the bytes for the category ivar. Things would go boom.

With a plain old subclass, things work because any code that can use the subclass' ivars knows about the subclass's ivars. But with a category, pre-existing code has no knowledge of the additions and won't properly create the space for them.

I suppose I should specify that all of the above is largely an educated guess. I could be totally wrong. It seems reasonable at least. :)

当你生成一个实例对象的时候,需要分配一定的足够大的内存,来表示这个对象。

举个例子,NSString类,被用到了很多系统框架中,被编译成库或者框架的形式,此时这些库或者框架已经知道NSString需要分配X个字节。

现在假如你想创建一个NSString的分类,并且添加了实例变量(假设可以),理论上,只要你的工程里其他的代码引入了这个分类(定义分类的头文件),这些代码就会知道NSString的内存大小现在为X+Y,这些后来编译的代码知道你已经对NSString做了扩展。

但是,之前已经编译好的模块(库、框架),它们没有引入你定义的分类,并不知道NSString内存大小发生了变化,当它们生成NSString的时候,仍然是X字节内存,并不是X+Y个字节,这样就发生了混乱。

上一篇下一篇

猜你喜欢

热点阅读