Short answer:
You subclass UIView
in order to inherit all the UIView
functionality and add custom functionality.
Long answer:
Your question pertains more to the idea of inheritance than the use of subclassing UIView
specifically. Inheritance is a simple concept, but can cause confusion if you are new to object oriented programming.
If you notice, all classes that you will commonly use when developing an iOS application inherit from NSObject
. NSObject
is the root class of most Objective-C classes, the main class method which NSObject provides (and subsequently any class which inherits NSObject) is alloc
(or new
depending on usage). This is why you can call [UIView alloc]
, as alloc is inherited through the class hierarchy. UIView
itself doesn't provide an implementation for alloc
, rather it inherits the method through NSObject
.
A simple and common example to illustrate inheritance uses animals. Let's say we have a super-class at the root of the hierarchy which all animals inherit from called Creature
. Now let's subclass Creature
to create a Mammal
class. The Mammal
class will inherit all the functionality (the public interface) of the Creature class
.
@interface Creature{
}
- (void)whatAmI;
@end
@implementation Creature
-(void)whatAmI{
NSlog(@"I am a Creature");
}
@end
@interface Mammal:Creature{
}
@end
Implement our Mammal
class:
Mammal *mammal1 = [[Mammal alloc]init];
[mammal1 whatAmI];
Output:
I am a Creature
Note that Mammal
inherits the -whoAmI
method from the parent class Creature
.You can now inherit from Mammal
and that subclass will inherit both the functionality of Mammal
and Creature
. The hierarchy of inheritance can continue.
If you want a firm understanding of Objective-C I recommend Programming in Objective-C by Steven Kochan.
Resources which discuss inheritance in Objective-C:
http://www.techotopia.com/index.php/Objective-C_Inheritance
http://www.tutorialspoint.com/objective_c/objective_c_inheritance.htm
Objective-C multiple inheritance