Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) without subclassing it.

like image 694
boom Avatar asked Mar 04 '10 07:03

boom


2 Answers

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.

like image 74
Laurent Etiemble Avatar answered Oct 16 '22 21:10

Laurent Etiemble


"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.

like image 3
Ben Zotto Avatar answered Oct 16 '22 20:10

Ben Zotto