Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is (overrides) in objective c

I'm following a tutorial on how to create a popover in Iphone here

what is (overrides) this code:

@interface UIPopoverController (overrides)
  + (BOOL)_popoversDisabled;
@end

@implementation UIPopoverController (overrides)

  + (BOOL)_popoversDisabled 
  { 
     return NO;
  }

@end
like image 531
liv a Avatar asked Feb 17 '23 18:02

liv a


1 Answers

This is an objective-C category. A category is a way of providing extra methods on a class, and they're useful in the following situations:

  • Extending a library class with domain-specific functionality. ie providing some extra features that will be useful for your application. This works whether or not you have the source-code for that class. For example, you could implement an [NSString asCreditCard] method or [UIColor applicationThemeColor].
  • Categories are also invaluable for grouping related functionality in a complex class.

Objective-C categories have the restriction that you cannot define additional ivars, and thus ivar-backed properties, on a category, although you can easily work around this using associative references - a run-time feature allowing you to link an object to a given class.

Associative References

To 'fake' a property or ivar on a category class use the following:

Define a 'key' to reference the associated property.

static char const* const carNamekey = "com.myObject.aKey"; 

The key doesn't necessarily have to have a value, since its the memory address of the object that is actually used.

Now, Implement the properties:

- (void) setCar:(Car*)car 
{
    objc_setAssociatedObject(self, &carNamekey, car, OBJC_ASSOCIATION_RETAIN_NONATOMIC);     
}

- (Car*) car 
{
    return objc_getAssociatedObject(self, &carNamekey);
}

If you wish you can add an @property declaration on the interface definition for the category, as an invitation to users of the class to use property-style (ie class.property = xxx) syntax.

Class Extensions

Another feature that is very similar to Objective-C categories is the class extension. A class extension is defined in the implementation block for a class like so:

@interface MyClass()

Some people refer to these as 'empty categories', but this is not quite correct. Unlike a category, a class extension will allow you to define additional properties and ivars on a class, without using associative references. This is useful for making a readonly property, internally writable, and things like that.

There - now you probably know more about categories than a lot of folks :)

like image 188
Jasper Blues Avatar answered Apr 06 '23 02:04

Jasper Blues