Your options:
1) Create a static C function to do it
static UIImageView* myfunc(CGFloat x, CGFloat y, CGFloat w, CGFloat h,
NSString* name, NSString* type, UIView* parent) {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:
CGRectMake(x,y,w,h)];
imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:name ofType:type]];
[self.view addSubView:imgView];
[imgView release];
return imgView;
}
2) Create a C macro
#define CREATE_ICON_VIEW(parent,x,y,w,h,name) \
...
3) Create an Objective-C static method
// in @interface section
+ (UIImageView*)addIconWithRect:(CGRect)rect name:(NSString*)name
type:(NSString*)type toView:(UIView*)view;
// in @implementation section
+ (UIImageView*)addIconWithRect:(CGRect)rect name:(NSString*)name
type:(NSString*)type toView:(UIView*)view {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:rect];
imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:name ofType:type]];
[self.view addSubView:imgView]; }
[imgView release];
return imgView;
}
// somewhere in app code
[MyClass addIconWithRect:CGMakeRect(0,0,32,32) name:@"ico-date"
type:@"png" toView:parentView];
4) Create an Objective-C category on UIImage or UIImageView
5) Create a method on the view that is to have a UIImageView added
- (void)addIconWithRect:(CGRect)rect name:(NSString*)name type:(NSString*)type {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:rect];
imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:name ofType:type]];
[self.view addSubView:imgView]; }
[imgView release];
return imgView;
}
6) Create a Helper class
Like option (3) but put the static methods in a separate class that's just for utility methods for repeated sections of code eg call the helper class "UIUtils".
7) Use a C inline function
static inline UIImageView* myfunc(CGFloat x, CGFloat y, CGFloat w, CGFloat h,
NSString* name, NSString* type, UIView* parent) {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:
CGRectMake(x,y,w,h)];
imgView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]
pathForResource:name ofType:type]];
[self.view addSubview:imgView];
[imgView release];
return imgView;
}
8) Use a loop to execute the same code repeatedly
9) Use an ordinary non-static Objective-C method
Personally I would go for none of these for your particular example and just write it out long-hand, unless it is repeated more than ten times in a file in which case I might go for (3). If its used in a lot of files I might go for (6).
Edit: Expanded descriptions for (3) and (6) and note about when I use (6).
Edit: Added options 8 & 9. Fixed memory leaks and some mistakes.
Edit: Updated code to use imageWithContentsOfFile instead of imageNamed.