开发者

how to add member variable and methods to in built class without subclassing it

How can I add member variables and methods to an in built class(say, NSString) 开发者_如何学JAVAwithout subclassing it.


For methods: you can use categories to add member methods without subclassing. It is a pretty common practice in Cocoa, to add per-framework extensions methods.

For instance variables: starting with Snow Leopard (Mac OS X 10.6), you can use associative references. You use them to simulate the addition of object instance variables to an existing class.

The Objective-C Programming Language is pretty comprehensive on what you can do with both associative references and categories.


"Categories" let you add methods, but not member variables, to existing classes.

See this tutorial's section on them (search in the page): http://cocoadevcentral.com/d/learn_objectivec/ Or look up Categories in Objective-C docs anywhere else.

You can't add instance vars without subclassing.


You can't. Sometimes it's a bad idea to subclass (maybe you're working with a class cluster, for example), so people often work around this by creating a brand new class (a subclass of NSObject, not of the class in question) which contains an instance variable whose type is the class in question, as well as the desired added variables.

For example, if you wanted to create a subclass of NSString with an additional BOOL called "foo"...

@interface StringWithFoo : NSObject
{
    NSString* string;
    BOOL foo;
}

... and then implement any methods you need, or create a public accessor so you can call methods on the string directly, or even use fancy runtime trickery to forward messages appropriately (ask a new question if that's what you want to do).

This is, loosely, an example of the decorator pattern.


You can add member methods to a class without subclassing by creating a category, but this will not allow you to add member variables.

Although a lot of stuff can be done at runtime in objective-c that can't be done in other languages (see runtime reference ) I really wouldn't suggest this much hackery to add an instance variable to an existing class.

Would you mind explaining the reason you do not want to subclass? A subclass or category really seems like the best thing to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜