Inheritance in Xcode for iOS (sample code)

In preparation for a forthcoming blogpost on self, super, polymorphism and inheritance in Xcode and iOS5, which has been inspired and informed by Matt Neuburg's book Programming iOS 5, I'm posting some sample (commented) code to illustrate the points that will be made. If you wish to experiment, then copy and paste this into your Xcode project.

For our inheritance example, this is the code contained within our initial view controller:
#import "ViewController.h"
#import "SquareView.h"
@interface ViewController ()
@end
@implementation ViewController : UIViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
SquareView *squareViewNew = [[SquareView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; // Creates a pointer to an instance of a SquareView object - note initWithFrame is inherited from UIView
[self.view addSubview:squareViewNew]; // Adds squareViewNew as subview to the view controller's view
[squareViewNew backgroundColorChange]; // backgroundColorChange is a SquareView instance method taken directly from SquareView class
squareViewNew.alpha = 0.5; // alpha property is inherited from UIView
UIView *nextResponder = (UIView *)[squareViewNew nextResponder]; // nextResponder instance method is inherited from UIResponder
nextResponder.backgroundColor=[UIColor greenColor]; // In this context it is the background that turns green
}
@end
and for completeness here are the SquareView.h
#import <UIKit/UIKit.h>
@interface SquareView : UIView
-(void)backgroundColorChange; // this is the single method we've added
@end
and SquareView.m files
#import "SquareView.h"
@implementation SquareView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
-(void)backgroundColorChange {
[self setBackgroundColor:[UIColor blueColor]]; // here's the implementation of the method we've created
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
@end
ViewController.h can be left untouched.
Illustrated here is the fact that since SquareView is a subclass of UIView it not only inherits all of the UIView properties and methods, but it also inherits those from UIResponder and NSObject.

Comments