L2P: The “Parts” of a Program - Hello World with a OOP Twist, Part 4
We have the project, we have the PrintCount class built, Now its time to use it! After this post, we will have our first, real, OOP program.
So what is our first pass at HelloOOP going to do? We are going to first create a instance of the PrintCount class. Then we will set a text string to that instance, print it out, and then print out the number of times we printed it.
The code for this program goes into the HelloOOP.m file that was created when we started the project. When you first hop into the HelloOOP.m file, you will notice a lot of code has already been pre-generated for you. Go ahead and delete the NSLog “Hello World” Line and add our code so it looks like the example below:
#import <Foundation/Foundation.h> #import "PrintCount.h" int main (int argc, const char * argv[]) { PrintCount * phraseA = [PrintCount alloc]; phraseA = [phraseA init]; [phraseA setText: @"This is Phrase A, Hello!"]; [phraseA printText]; [phraseA printNum]; [pool drain]; return 0; }
So what is this code doing? Lets go over it line by line:
-
1. Importing the Foundation.h library
2. Importing the header file for our PrintCount class
4. Starting the main section of code (The stuff the parenthesises allows us to send varaibles to the program, nothing we need to worry about now)
6. Sets up some memory management for our program, Nothing we need to worry about now
8. Allocates the memory for a new instance of PrintCount class called phraseA, This is step 1 of starting our instance
9. Initializes the phraseA instances, this is the 2nd step and completes the initalization
11. Calls the setText method of phraseA with an argument of the NSString indicated
12. Calls the printText method of phraseA
13. calls the printNum method of phraseA
15. De-allocates any remaining variables to clear the memory
16. Returns 0 to the program, this indicates an error free run of the code
17. Closes the main section of code
So now lets run the code. First lets open the console by going to the “Run” menu and select “Console”. Now click the Built and Run button in your project window. If it builds without error you should get something similar the following output in your console window:
2011-03-04 12:26:29.944 HelloOOP[8520:a0f] This is Phrase A, Hello!
2011-03-04 12:26:29.949 HelloOOP[8520:a0f] The string 'This is Phrase A, Hello!' has been printed 1 times
If you got this, Congrats! If not, look back over the code and figure out what failed. Feel free to post in the comments and I'll try to help. Next up we will play around with our class and explore the power of OOP.





Comments
Post new comment