Lets say i have a little bit of code I would like to repeat a number of times. How should I best include this in my iPhone app to only have to write this once?
Its a typical TableView Controller App.
//Set Icon
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(30,25,20,20)];
imgView.image = [UIImage imageNamed:@"ico-date.png"];
[self.view addSubview:imgView];
Regards
Your options:
1) Create a static C function to do it
2) Create a C macro
3) Create an Objective-C static method
4) Create an Objective-C category on UIImage or UIImageView
5) Create a method on the view that is to have a UIImageView added
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
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.