In Objective-C, why class-continuation can add instance variables but class category can't? -
i know can't add instance variables in class category, can add in class-continuation, can 1 tell me why or give me detail it. know can use associate in category, want know detail implementation cause this. lot .
tl;dr
class extensions modify classes own, whereas categories can modify existing class.
adding ivars existing classes can break binary compatibility in old runtimes (prior ios or osx 64-bit), that's why forbidden.
adding methods not suffer problem, since method resolution has been dynamic.
discussion
because class extensions (what clang calls class continuations) not categories, although have in common.
from apple documentation
a class extension bears similarity category, it can added class have source code @ compile time (the class compiled @ same time class extension). methods declared class extension implemented in
@implementation
block original class can’t, example, declare class extension on framework class, such cocoa or cocoa touch class nsstring.
a class extensions extends interface of class @ compile time: it's simple matter of code organization , visibility (it useful, instance, declare private properties).
you breaking @interface
declaration multiple parts, cannot add existing class don't own.
adding ivar naturally supported reason. can do:
@interface myclass : nsobject { nsinteger a; nsinteger b; } @end
or
@interface myclass : nsobject { nsinteger a; } @end @interface myclass() { nsinteger b; } @end
and it's almost equivalent (if place class extension in private .m file b
private).
on other hand, class category can modify any class.
this crucial, since when categories designed, objective-c had fragile base ivars.
what mean? means once class compiled, ivars layout fixed forever in binary , cannot modify without breaking binary compatibility subclass of class.
therefore, adding ivar to, say, nsobject
break (almost) every class in every framework ever compiled.
conversely, methods dynamically resolved can safely add method existing class, long don't have name clashes.
the fragile ivar problem has been tackled since first ios (iphone os @ time) , 64-bit osx use of dynamic ivars, objective-c cannot take advantage of feature without breaking compatibility 32-bit macs.
references
http://www.sealiesoftware.com/blog/archive/2009/01/27/objc_explain_non-fragile_ivars.html http://www.cocoawithlove.com/2010/03/dynamic-ivars-solving-fragile-base.html
Comments
Post a Comment