Intro to Object-Oriented Design: Part 1/2
This tutorial series will teach you the basics of object-oriented design. In this first part: Inheritance, and the Model-View-Controller pattern. By Ellen Shapiro.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Intro to Object-Oriented Design: Part 1/2
40 mins
- Getting Started
- The Basics Of Objects
- A Minor Digression: Under The Hood With Properties
- Describing the Object
- A Minor Digression: Class Methods vs. Instance Methods
- Adding Basic Methods to Your Class
- Inheritance
- Overriding Methods
- Building out the User Interface
- Hooking Your Data to Your View
- Model-View-Controller Encapsulation of Logic
- Creating Subclasses via Inheritance
- Housing Logic in the Model Class
- Where To Go From Here?
Housing Logic in the Model Class
You can also use this approach to keep some of the more complicated logic encapsulated within the model class. Think about a Truck object: many different types of vehicles are referred to as a “truck”, ranging from pickup trucks to tractor-trailers. Your truck class will have a little bit of logic to change the truck's behavior based on the number of cubic feet of cargo it can haul.
Go to File\New\File\CocoaTouch\Objective-C Class, and create a new subclass of Vehicle called Truck.
Add the following integer property to Truck.h to hold the truck's capacity data:
@property (nonatomic, assign) NSInteger cargoCapacityCubicFeet;
Since there are so many different types of trucks, you don't need to create an init method that provides any of those details automatically. You can simply override the superclass methods which would be the same no matter the size of the truck.
Open Truck.m and add the following methods:
#pragma mark - Superclass overrides
- (NSString *)goForward
{
return [NSString stringWithFormat:@"%@ Depress gas pedal.", [self changeGears:@"Drive"]];
}
- (NSString *)stopMoving
{
return [NSString stringWithFormat:@"Depress brake pedal. %@", [self changeGears:@"Park"]];
}
Next, you’ll want to override a couple of methods so that the string returned is dependent on the amount of cargo the truck can haul. A big truck needs to sound a backup alarm, so you can create a private method (i.e., a method not declared in the .h file and thus not available to other classes) to do this.
Add the following helper method code to Truck.m:
#pragma mark - Private methods
- (NSString *)soundBackupAlarm
{
return @"Beep! Beep! Beep! Beep!";
}
Then back in the superclass overrides section, you can use that soundBackupAlarm
method to create a goBackward method that sounds the alarm for big trucks:
- (NSString *)goBackward
{
NSMutableString *backwardString = [NSMutableString string];
if (self.cargoCapacityCubicFeet > 100) {
//Sound a backup alarm first
[backwardString appendFormat:@"Wait for \"%@\", then %@", [self soundBackupAlarm], [self changeGears:@"Reverse"]];
} else {
[backwardString appendFormat:@"%@ Depress gas pedal.", [self changeGears:@"Reverse"]];
}
return backwardString;
}
Trucks also have very different horns; a pickup truck, for instance, would have a horn similar to that of a car, while progressively larger trucks have progressively louder horns. You can handle this with some simple if/else statements in the makeNoise
method.
Add makeNoise as follows:
- (NSString *)makeNoise
{
if (self.numberOfWheels <= 4) {
return @"Beep beep!";
} else if (self.numberOfWheels > 4 && self.numberOfWheels <= 8) {
return @"Honk!";
} else {
return @"HOOOOOOOOONK!";
}
}
Finally, you can override the vehicleDetailsString
method in order to get the appropriate details for your Truck object. Add the method as follows:
-(NSString *)vehicleDetailsString
{
//Get basic details from superclass
NSString *basicDetails = [super vehicleDetailsString];
//Initialize mutable string
NSMutableString *truckDetailsBuilder = [NSMutableString string];
[truckDetailsBuilder appendString:@"\n\nTruck-Specific Details:\n\n"];
//Add info about truck-specific features.
[truckDetailsBuilder appendFormat:@"Cargo Capacity: %d cubic feet", self.cargoCapacityCubicFeet];
//Create the final string by combining basic and truck-specific details.
NSString *truckDetails = [basicDetails stringByAppendingString:truckDetailsBuilder];
return truckDetails;
}
Now that you’ve got your Truck object set up, you can create a few instances of it. Head back to VehicleListTableViewController.m and add the following import to the top of the file so that it knows about the existence of the Truck class:
#import "Truck.h"
Find the setupVehicleArray
method and add the following code right above where you sort the array:
//Create a truck
Truck *silverado = [[Truck alloc] init];
silverado.brandName = @"Chevrolet";
silverado.modelName = @"Silverado";
silverado.modelYear = 2011;
silverado.numberOfWheels = 4;
silverado.cargoCapacityCubicFeet = 53;
silverado.powerSource = @"gas engine";
//Add it to the array
[self.vehicles addObject:silverado];
//Create another truck
Truck *eighteenWheeler = [[Truck alloc] init];
eighteenWheeler.brandName = @"Peterbilt";
eighteenWheeler.modelName = @"579";
eighteenWheeler.modelYear = 2013;
eighteenWheeler.numberOfWheels = 18;
eighteenWheeler.cargoCapacityCubicFeet = 408;
eighteenWheeler.powerSource = @"diesel engine";
//Add it to the array
[self.vehicles addObject:eighteenWheeler];
This will create a couple of Truck objects with the truck-specific properties to join the cars and motorcycles in the array.
Build and run you application; select one of the Trucks to verify that you can now see the appropriate Truck-specific details, as demonstrated below:
That looks pretty great! The truck details are coming through thanks to the vehicleDetailsString
method, inheritance, and overridden implementations.
Where To Go From Here?
You can download a copy of the project up to this point.
You've set up a base Vehicle class with Car, Motorcycle, and Truck subclasses, all listed in the same table view. However, there’s no way to verify that all of your truck's size-specific handling is working correctly.
Part 2 of this tutorial will fill out the rest of the app to display more vehicle details. Along the way, you'll learn about polymorphism and a couple of additional major design patterns for Object-Oriented Programming.
Until then, why not try implementing a Bicycle class or a few more custom properties to some of the vehicle subclasses? Or you can read up on Apple's reference guide Object-Oriented Programming with Objective-C.
Got questions? Ask away in the comments below!