views:

546

answers:

3

Is the concept of the Objective-C categories in anyway similar to the concept of mixins? If so: what are the similarities? In not: what are the differences?

+1  A: 

Categories are defined for a particular class, as far as I know, you can't create a category and add the methods it implements to several classes.

pgb
+1  A: 

With a mixin, you might derive a new class from your base and the mixin, then instantiate this new class to take advantage of it.

With a category, you are effectively adding directly the base class, so that all instances of that base have access to the functionality provided by the category.

Paul Dixon
+3  A: 

To the best of my understanding:

Mixins

  • Syntactic sugar for composition
  • Added by the developer of the class, not the user
  • Can be reused by multiple classes
  • Can add instance variables
  • Can be implemented using forwarding in Objective-C

Categories

  • Similar to extension methods in other languages
  • Usually added by the user of the class, not the developer
  • Used by exactly one class and its subclasses
  • Can't add instance variables
John Calsbeek
In some languages (ie. Ruby), mixins don't allow instance variables
Casebash