Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

objective c - Why can't categories have instance variables?

I understand we can use associative references to invoke ivar-like behavior in categories. But what's the specific reason behind not being able to declare new ivars in categories?

Is it because we would invade the private space of the class? Or is there any other reason? If yes, I would appreciate an example that shows the ability to declare ivars in categories breaking whatever it breaks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...