views:

95

answers:

2

What sort of Objective-C runtime magic do I need to use to make it so a property for an object is always set to a value than its normal default. For example, UIImageView's userInteractionEnabled is always false, but I want to my own UIImageview subclass to always have userInteractionEnabled set to true. Is the same thing achievable without subclassing UIImageView?

A: 

Create a category with an init method and/or convenience constructor that sets the property for you. Setting values in the constructor is how pretty much all "object defaults" are handled in Objective-C, and fortunately categories let you add any functionality you like to a class as long as it doesn't require extra instance variables.

Chuck
+1  A: 

You could create a new category for UIImageView and add a new initializer:

// UIImageView(CustomInitialization).h
@interface UIImageView (CustomInitialization)

- (id)customInitWithImage:(UIImage *)image;

@end


// UIImageView(CustomInitialization).m
#import "UIImageView(CustomInitialization).h"

@implementation UIImageView (CustomInitialization)

- (id)customInitWithImage:(UIImage *)image
{
    if (self = [self initWithImage:image])
    {
        self.userInteractionEnabled = YES;
    }
}

@end

You will need to include UIImageView(CustomInitialization).h in your code, and then call your initializer every time you want the default properties set:

UIImageView * iview = [[UIImageView alloc] customInitWithImage:[UIImage imageNamed:@"pic.png"]];

Marco Mustapic
Should I do this inside the image property instead? Since UIImageView can be created without image set to it (e.g. created in Interface Builder with no image set)
Boon