2. Overview
Objective-C is an object oriented language.
follows ANSI C style coding with methods
from Smalltalk
Flexible almost everything is done at runtime.
Dynamic Binding
Dynamic Typing
Dynamic Linking
3. Inventors
Objective-C was invented by two men,
Brad Cox and Tom Love.
Both were introduced to Smalltalk at ITT in
1981
Cox thought something like Smalltalk
would be very useful to application
developers
Cox modified a C compiler and by 1983 he
had a working Object-oriented extension to
C called OOPC.
4. Development
Tom Love acquired a commercial copy
of Smalltalk-80 while working for
Schlumberger Research
With direct access Smalltalk, Love
added more to OOPC making the final
product, Objective-C.
In 1986 they release Objective-C
through their company “Stepstone”
5. NeXT and NeXTSTEP
In 1988 Steve Jobs acquires Objective-
C license for NeXT
Used Objective-C to build the
NeXTSTEP Operating System
Objective-C made interface design for
NeXTSTEP much easier
NeXTSTEP was derived from BSD Unix
In 1995 NeXT gets full rights to
Objective-C from Stepstone
6. OPENSTEP API
Developed in 1993 by NeXT and Sun
An effort to make NeXTSTEP-like
Objective-C implementation available to
other platforms.
In order to be OS independent
Removed dependency on Mach Kernel
Made low-level data into classes
Paved the way for Mac OS X, GNUstep
7. Apple and Mac OS X
NeXT is taken over by Apple in 1996
and put Steve Jobs and his Objective-C
libraries to work
Redesigned Mac OS to use objective-C
similar to that of NeXTSTEP
Developed a collection of libraries
named “Cocoa” to aid GUI development
Release Mac OS X (ten), which was
radically different than OS 9, in March
2001
8. The Cocoa API
Developed by Apple from NeXTSTEP and
OPENSTEP
Has a set of predefined classes and types
such as NSnumber, NSstring, Nsdate, etc
.
NS stands for NeXT-sun
Includes a root class NSObject where words
like alloc, retain, and release come from
9. Dynamic Language
Almost everything is done at runtime
Uses dynamic typing, linking, and
binding
This allows for greater flexibility
Minimizes RAM and CPU usage
10. To Import or Include?
C/C++’s #include will insert head.h into
the code even if its been added before.
Obj-C’s #import checks if head.h has
been imported beforehand.
#import “head.h”
15. Address and Pointers
Same as C
To get address of a variable i
&i
Pointer
int *addressofi = &I;
16.
17. Conditionals and Loops
Same as C/C++
if / else if/ else
for
while
break
ontinue
do-while
for(int i=0; i< 22; i++) {
printf(“Checking i=“@dn”, i);
if(i+90 == i*i)
{ break;}
18. for in loop
Introduced in Objective-C 2.0 (“fast enumeration”)
for(Item_Type *item in Collection_of_Items) {
//do whatever with the item
Nslog(@” Looking now at %@”, item);
}
Note: %@ in the NSLog
converts whatever is passed
(in this case item) to a string
19. Functions
Same as C/C++
return_type functionName(type v1, type v2, ….)
{ //code of function
}
Example
void showMeInfo(int age)
{
printf(“You are %d years old”, age); //or use NSLog()
}
20. Global and static variables
Same as C/C++
Global variables defined at top of file
For static variables use keyword static before it
static in CurrentYear = 2013;
21. Functions --- pass by reference
Same as C/C++
return_type functionName(type v1, type *v2, ….)
{ //code of function
}
Example – call above
int v1 = 2;
int v2 = 3;
functionName(v1, &v2);
22. Main Funciton –like C++
#import <whatever/what.h>
int main(int argc, const char *argv[])
{
@autoreleasepool {
//your code here*******
//you can have C code if you wish or Objective-C
return 0;
}
}
NOTE: Latest version of Objective-C uses Automatic
Reference Counting (kind of like automatic garbage collection)
----to handle getting rid of not needed items in memory (avoiding
memory leaks). YEAH! AUTOMATIC!
-----like Java this way
@autoreleasepool in a needed annotation around your main
block of code to “enable” this
23. IMPORTANT --- we are doing iOS
applications NOT mac OS applications
We will be doing iOS application that have a different
framework called Model View Controller ----
But, for some examples to learn concepts of Objective-C
we will show some basic main.m files with main functions
that are not iOS programs!!!
We will learn iOS soon!
24. Main Function –like C++
#import <whatever/what.h>
int main(int argc, const char *argv[])
{
@autoreleasepool { //takes care of “automatic release of not needed items
//static method date with no parameters is invoked on NSDate class
NSDate *now = [NSDate date]; //this will generate a new instance of NSDate with current time
NSLog(@”The new date lives at %p”, now); //Objective-C function that is like printf to console
double seconds = [now timeIntervalSince1970] //call timesInterrval* method on now object
NSLog(@”It has been %f seconds since 1970”, seconds);
NSDate *later = [now dateByAddingTimeInterval:100000]; //pass 100000 parameter to method
NSLog(@”In 100,000 seconds will be %@”, later); //%@ means print as string
return 0;
}
}
25.
26. Non-GUI – text output
Two standard functions you see used
printf() – same as C
○ printf(“Hi Lynne”); //this is actual C code
NSLog()
○ NSLog(@”Hi Lynne”); //this is strictly Objective-C
27.
28. Classes
Have both definition file and
implementation file : classname.h and
classname.m
Similar to how have .h and .cpp in C++
30. Declaring methods
C++ syntax
Objective-C syntax
void function(int x, int y, char z);
Object.function(x, y, z);
-(void) method:(int)x, (int)y, (char)z;
[Object function:x, y, z];
-(return type) function_name: (type) p1, (type) p2, ***;Apply function to Object
passing parameters x,y,z
31. Whats this + and – stuff?
When declaring or implementing
functions for a class, they must begin
with a + or -
+ indicates a “class method” that can
only be used by the class itself. (they are
like static methods in Java invoked on class itself)
- indicates “instance methods” to be
used by the client program (public
functions) –invoked on an object / class
instance . (they are like regular methods in
Java invoked on object)
34. Class Declaration (Interface)
#import <Cocoa/Cocoa.h>
@interface Node : NSObject {
Node *link;
int contents;
}
+(id)new;
-(void)setContent:(int)number;
-(void)setLink:(Node*)next;
-(int)getContent;
-(Node*)getLink;
@end
Node.h
Class is Node who’s
parent is NSObject
{ class variables }
+/- private/public methods
of Class
Class variables are private
35. Class Definition (Implementation)
#import “Node.h”
@implementation Node
+(id)new
{ return [Node alloc];}
-(void)setContent:(int)number
{contents = number;}
-(void)setLink:(Node*)next {
[link autorelease];
link = [next retain];
}
-(int)getContent
{return contents;}
-(Node*)getLink
{return link;}
@end
Node.m
Like your C++
.cpp file
>>just give
the methods
here
36.
37. Creating class instances
ClassName *object = [[ClassName alloc] init];
ClassName *object = [[ClassName alloc] initWith* ];
NSString* myString = [[NSString alloc] init];
Nested method call. The first is the alloc method called on NSString itself.
This is a relatively low-level call which reserves memory and instantiates
an object. The second is a call to init on the new object. The init
implementation usually does basic setup, such as creating instance
variables. The details of that are unknown to you as a client of the class.
In some cases, you may use a different version of init which takes input:
ClassName *object = [ClassName method_to_create];
NSString* myString = [NSString string];
Some classes may define a special method that will in essence call alloc followed by
some kind of init
Creating an Object
39. Messages ---really weird (new) syntax
Almost every object manipulation is done
by sending objects a message
Two words within a set of brackets, the
object identifier and the message to send.
Like C++ or Java’s Identifier.message()
[Identifier message ]
40. Setting values for class variables of
an object ---- THROUGH methods
[object methodName];
[object
setXXXMethod:value1];
[object
setYYYYMethod:value2];
41. C++ VS. Objective-C
Adds OOP,
metaprogramming
and generic
programming to C
Comes with a std
library
Has numerous uses
Large and complex
code for OOP
Only adds OOP to C
Has no standard
library; is dependant
on other libraries
Mostly used for
application building
Simpler way of
handling classes
and objects
42. Keyword: id
The word ‘id’ indicates an identifier for an
object much like a pointer in c++
This uses dynamic typing
For example, if Pen is a class…
extern id Pen;
id myPen;
myPen = [Pen new ];
id work like pointers to objects.
43. Memory Allocation
Objects are created dynamically through
the keyword, “alloc”
Objects are automatically deallocated in
latest Objective-C through automatic
reference counting
44. Automatic Reference Counting
Objective C uses ‘AUTOMATIC reference
counting' as memory management
keeps an internal count of how many times
an Object is 'needed'.
System makes sure that objects that are
needed are not deleted, and when an
object is not needed it is deleted.
45. iOS programs and
@autoreleasepool
You will notice (later when you learn)
your iOS applications are setup in
Xcode (the IDE) with @autoreleasepool
setup
This insures automatic release of
unneeded items will take place for you.
46.
47. linkList class
#import "linkList.h"
@implementation linkList
+(id)new
{return [linkList
alloc];}
-(void)insert:(int)value
{
id temp = [Node new];
[temp
setContent:value];
[temp setLink:head];
head = [temp retain];
[temp release];
}
-(void)append:(int)value {
id last = [head getLink];
while ([last getLink] !=
nil)
{last = [last getLink];}
id temp = [Node new];
[temp setContent:value];
[last setLink:temp];
[temp release];
}
-(void)remove {
id temp = head;
head = [head getLink];
[temp release];
}
-(int)getValue {
return [head
getContent];}
@end
linkList.m
Class linkList is child of
previous Node class
(not showing .h file for brevity)
48. Stack class (child of linkList)
#import "linkList.h”
@interface Stack : linkList
{}
+(id)new;
-(void)push:(int)value;
-(int)pop;
@end
#import "stack.h”
@implementation Stack
+(id)new
{return [Stack alloc];}
-(void)push:(int)value
{[self insert:value];}
-(int)pop {
int ret = [self getValue]; //getValue metho
of parent linkList
[self remove]; //remove method of parent
linkList
return ret;
}
@end
stack.h stack.m
self is like the C++/Java word this.
Remember alloc creates the
object in memory
49. Example: main.m
#import "stack.h”
int main(){
Stack *s = [Stack new];
[s push:1];
[s push:2];
printf("%dt", [s pop]);
[s push:3];
printf("%dt", [s pop]);
printf("%dt", [s pop]);
[s release];
return 0;
}
Run the program :
2 3 1
new is method defined in Stack class
that simply that calls [Stack alloc]
--- done for convinience
Note only need to import “stack.h” because
stack imports LinkList.h which imports Node.h
which imports cocoa.h
release is method to release this
object s explicitly from memory
52. NSInteger and NSUnteger
NSInteger number; (Like long in C)
NSUItneger another; (Like unsigned long in C)
Objective-C data types that are 32-Bits on 32-
Bit platforms and 64-bits on 64-bit platforms
53. NSString
NSString *theMessage = @”hello world”;
Number of characters in a string
○ NSUInteger charCount = [theMessage length];
Test if 2 strings equal
○ if([string_var_1 isEqual: string_var_2])
{ //code for equal case }
54. String literal in Objective-C
Begins with the @ symbol
@”Lynne Grewe”;
Some Examples
NSString *myString = @”Hello World”;
int len = [myString length];
OR
int len = [@”Hello World” length];
OR
NSString *myString = [[NSString alloc] initWithString:@”Hello World”];
int len = [myString length];
This is like “Lynne Grewe” in most other languages
55. Formatting Strings in output
NSLog
int a = 1;
float b = 33.22;
char c = ‘A’;
NSLog(@”Integer %d Float: %f Char: %c”, a, b, c);
56. NSString ---not changeable
International (any language) strings using Unicode.
Compiler will create an NSString for you using @“foo”
notation.
An NSString instance can not be modified! They are
immutable.
Usual usage pattern is to send a message to an NSString
and it will return you a new one.
self.display.text = [self.display.text stringByAppendingString:digit];
self.display.text = [NSString stringWithFormat:@“%g”, brain.operand]; // class method
Tons of utility functions available (case conversion, URLs,
substrings, type conversions, etc.).
Used throughout iOS instead of C language’s char * type.
57. NSMutableString ---changeable
Mutable version of NSString. Somewhat rarely used.
Can do some of the things NSString can do without creating
a new one (i.e. in-place changes).
NSMutableString *ms = [[NSMutableString alloc] initWithString:@“0.”];
NSMutableString *ms = [NSMutableString stringWithString:@“0.”]; // inherited from NSString
[ms appendString:digit];
58. NSNumber
Object wrapper around primitive types like int,
float, double, BOOL, etc.
NSNumber *num = [NSNumber numberWithInt:36];
float f = [num floatValue]; // would return 36 as a float (i.e. will convert types)
Useful when you want to put multiple numeric
primitive types in a collection (e.g. NSArray or
NSDictionary).
59. NSValue
Generic object wrapper for other non-
object data types.
CGPoint point = CGPointMake(25.0, 15.0); // CGPoint is a C struct
NSValue *pointObject = [NSValue valueWithCGPoint:point];
60. NSData
“Bag of bits.” Used to
save/restore/transmit data throughout
the iOS SDK.
61. NSDate
“Used to find out the time right now or to
store past or future times/dates.
See also NSCalendar,
NSDateFormatter, NSDateComponents.
62. NSArray – holds fixed array of
points to objects
NSArray *thearray = [NSArray arrayWithObjects:o1,o2,o3,o4, nil];
//get element
[thearray objectAtIndex:0]; //element at index 0
Example
NSDate *now = [NSDate date];
NSDate *tomorrow = [now dateByAddingTImeInterval:24.0*60.0*60.0]; //add a day
NSDate *yesterday = [now dateByAddingTimeInterval:-24.0*60.0*60.0]; //minus a day
//array of Dates
NSArray *dateList = [NSArray arrayWithObjects:now, tomorrow, yesterday];
//get elements in array
NSDate *first = [dateList objectAtIndex:0];
Methods are:
count = gets number of items in array
objectAtIndex:i = returns element i of array (starting from 0)
Note: you can not add or remove a pointer from an NSArray
---fixed once created
63. NSArray – cycle through with for
loop
NSDate *now = [NSDate date];
NSDate *tomorrow = [now dateByAddingTImeInterval:24.0*60.0*60.0]; //add a day
NSDate *yesterday = [now dateByAddingTimeInterval:-24.0*60.0*60.0]; //minus a day
//array of Dates
NSArray *dateList = [NSArray arrayWithObjects:now, tomorrow, yesterday];
//get elements in array
NSDate *first = [dateList objectAtIndex:0];
NSUInteger dateCount = [dateList count];
for(int i=0; i<dateCount; i++)
{ NSDAte *d = [dateList objectAtIndex:i];
NSLog(@” Date is %@”, d);
}
Methods are:
count = gets number of items in array
objectAtIndex:i = returns element i of array (starting from 0)
64. NSArray – cycle through with for
loop OPTION 2
NSDate *now = [NSDate date];
NSDate *tomorrow = [now dateByAddingTImeInterval:24.0*60.0*60.0]; //add a day
NSDate *yesterday = [now dateByAddingTimeInterval:-24.0*60.0*60.0]; //minus a day
//array of Dates
NSArray *dateList = [NSArray arrayWithObjects:now, tomorrow, yesterday];
//get elements in array
NSDate *first = [dateList objectAtIndex:0];
For(NSDate *d in dateList)
{ NSDAte *d = [dateList objectAtIndex:i];
NSLog(@” Date is %@”, d);
}
This is a “for in” loop --- convinient
65. NSMutableArray – changeable array
of pointers to objects.
NSMutableArray *thearray = [NSArray arrayWithObjects:o1,o2,o3,o4, nil];
//get element
[thearray objectAtIndex:0]; //element at index 0
Example
NSDate *now = [NSDate date];
NSDate *tomorrow = [now dateByAddingTImeInterval:24.0*60.0*60.0]; //add a day
NSDate *yesterday = [now dateByAddingTimeInterval:-24.0*60.0*60.0]; //minus a day
//array of Dates
NSMutableArray *dateList = [NSMutableArray array];
//set elements
[dateList addObject:now];
[dateList addObject:tomorrow];
[dateList addObject:yesterday];
Methods are:
array = gets empty NSMutableArray
addObject:obj = adds as next element the obj
to array
Note: you can add or remove a pointer from an NSMutableArray
66. NSMutableArray – adding element
at Index location
[arrayName insertObject:obj atIndex:i]
Example -- put in at beginning of array
[dateList insertObject:yesterday atIndex:0]
67. NSMutableArray – removing an
element
[arrayName removeObjectAtIndex:i]
Example
[dateList removeObjectAtIndex:0] //get rid of 1st
element
68. NSDictionary
Immutable hash table. Look up objects using a
key to get a value.
+ (id)dictionaryWithObjects:(NSArray *)values forKeys:(NSArray *)keys;
+ (id)dictionaryWithObjectsAndKeys:(id)firstObject, ...;
Creation example:
NSDictionary *base = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:2], @“binary”,
[NSNumber numberWithInt:16], @“hexadecimal”, nil];
Methods
- (int)count;
- (id)objectForKey:(id)key;
- (NSArray *)allKeys;
- (NSArray *)allValues;
70. NSMutableSet
Changeable version of NSSet
Methods
- (void)addObject:(id)anObject; // does nothing if object that isEqual:anObject is already in
- (void)removeObject:(id)anObject;
- (void)unionSet:(NSSet *)otherSet;
- (void)minusSet:(NSSet *)otherSet;
- (void)intersectSet:(NSSet *)otherSet;
see documentation (apple.com) for more details
72. Cycling through Collections
classes ---- use for-in loop
Example: NSArray of NSString
NSArray *myArray = ...;
for (NSString *string in myArray) { // no way for compiler to know what
// myArray contains
double value = [string doubleValue]; // crash HERE if string not an NSString
}
73. NSSet example for-in loop
Example: NSSet of id
NSSet *mySet = ...;
for (id obj in mySet) {
// do something with obj, but make sure you
//don’t send it a message it does not respond to
if ([obj isKindOfClass:[NSString class]]) {
// send NSString messages to obj with impunity
}
}
74. NSDictionary example for-in
loop
Example: NSDictionary
NSDictionary *myDictionary = ...;
for (id key in myDictionary) {
// grab value associated with the current key
id value = [myDictionary objectForKey:key];
// do something with value here ***
}
75. Property list (plist)
A collection of collections
Specifically, it is any graph of objects containing only the following
classes:
○ NSArray, NSDictionary, NSNumber, NSString, NSDate, NSData
Example1 : NSArray is a Property List if all its members are too --- NSArray
of NSString is a Property List
--- NSArray of NSArray as long as those NSArray’s members are Property
Lists.
Example 2: NSDictionary is one only if all keys and values are too
Why define this term?
Because the SDK has a number of methods which operate on Property Lists.
Usually to read them from somewhere or write them out to somewhere.
[plist writeToFile:(NSString *)path atomically:(BOOL)]; // plist is NSArray or
NSDictionary
We will see this in
practice later
76. NSUserDefaults
Lightweight storage of Property Lists.
an NSDictionary that persists between
launches of your application.
Not a full-on database, so only store
small things like user preferences.
77. NSUserDefaults continued
Read and write via a shared instance obtained
via class method standardUserDefaults
[[NSUserDefaults standardUserDefaults] setArray:rvArray forKey:@“RecentlyViewed”];
Methods (some)
- (void)setDouble:(double)aDouble forKey:(NSString *)key;
- (NSInteger)integerForKey:(NSString *)key; // NSInteger is a typedef to 32 or 64 bit
int
- (void)setObject:(id)obj forKey:(NSString *)key; // obj must be a Property List
- (NSArray *)arrayForKey:(NSString *)key; // will return nil if value for key is not
NSArray
Always remember to write the defaults out after
each batch of changes!
[[NSUserDefaults standardUserDefaults] synchronize];
78.
79. CONCLUSION --- a note---Objective-C
2.0 – some features that were added
In October 2007, Apple Inc. releases
Objective-C 2.0 for Mac OS 10.5
(Leopard)
Adds automatic garbage collection
(ARC)
Instance Methods (public functions) are
defined differently using @property
---see next lecture
Notes de l'éditeur
What is objective-C? Well, for starters it’s a programming language. More specifically it’s a completely object oriented programming language. It can be described as having descended from of Smalltalk and C. Since it uses a modified C compiler and can be implemented with C code.
It borrows an object manipulation method (the syntax) from Smalltalk.
Unlike C and C++, there is no formal written standard. It must rely on other libraries or else the make have the client make their own from scratch.
This is also a dynamic language, where very little is done at compile-time. Using dynamic typing, linking and binding, it allows for more flexibility when running.
Brad Cox and Tom Love both were at an ITT tech center were they were introduced to Smalltalk and object Oriented programming. Cox took a vested interest in OOP as he thought it would be invaluable in building powerful Developer environments for system developers. In 1983, he started modifying a C compiler to use OOP, and eventually came up with a working extention called OOPC which stands for “Object Oriented Programming in C”
Love meanwhile was hired by Schlumberger Research and had the opportunity to work with one of the first commercial copies of Smalltalk-80. Love with is first hand experience and with direct access to Smalltalk, he adds more to OOPC creating the first release Objective-C.
The language is released 1986 through the company they created called “stepstone”.
That same year Brad Cox writes his book &lt;show book&gt; which describes the language, or an early form of it somewhat. If you want to know more about Obj-C, you should go check it out.
In 1988 Steve Jobs who left Apple to start the NeXT Software company, gets a license to use Objective-C from Stepstone. His company then uses it to build an OS for his NeXT computers. Their new Operating System NeXTSTEP was built from the Mach Kernel from BSD Unix, and with Objective-C, interface design and implementation was pretty easy.
NeXTSTEP demonstrates the use of Obj-C in practical terms. Since Obj-C has no std lib of its own, NeXT basically wrote the primary implementation of objective-C, they eventually get the rights for Objective-C. Soon other machines wanted to use something like NeXTSEP.
So they started to develop OPENSTEP jointly with Sun Microsystems. Unlike NextStep, which was an OS and a set of libraries, they wanted to make just an OS independent set of libraries. That would mean removing all dependencies on the Mach Kernel that was in NeXTSTEP and BSD. They also made low level data types into classes, a low level data would be something like strings or datestamps, into classes named NSString or NSDate, Where NS stands for NeXT-sun (the developes). I’ll talk more about them later.
In 1996, Steve Jobs’ former place of employment comes in and takes over NeXT and with it, NeXTstep and Objective-C. So then Apple puts them all to work, Jobs included. Since NeXTStep worked wonderfully, they decided to implement it into their Mac OS family of OSes. From NextStep they develop a new API which they called “Cocoa” to work with Objective-C which was Apple’s now. From NeXTSTEP, which was from BSD, they made MAC OS ten. OS ten was radically different than their previous MAC Oses, which sets Apple Inc. forward to new futures.
The Cocoa API is now days more frequnetly used when using Objective-C. Cocoa saw influence from OpenStep and Nextstep. In that they use NSObjects like in Openstep. Almost any object made in cocoa must inheret from NSObject in order to use the methods frovided by the framework.
Objective-C is a wholly dynamic language. Dynamic typing allows minimal memory usage as the OS does not need to keep track of what things are untill they need to use them. DB means it won’t have to merge function calls with parameters until it needs to run them. An DL allows more things to be added to the program while it runs. All 3 aspects are perfect for running an OS where changes can be made while the system is still running.
Obj-C introduces a precompile command “Import” which unlike C and C++’s include would check to see weather or not the file (in this case “head.h”) has been imported before. If the file has been added before, then it will not import it again. This is to eliminate the redundancy of adding the same file over and over again. And to prevent compilation errors when duplicate functions are declared.
Importing will aid in inheritence and adding classes to a program, because one import could call so many other imports so you’ll need as little as one import.
A brief overview of syntax structure.
Read Slide
A + would be used for something like object allocation (constructor), which is the only thing I seen it sued for, so I’m not sure if it can be used for other things. Primarily the id is a Class in this case
In our .h file, we put The name of the class after the word @interface followed by its superclass. Since I’m using cocoa, its superclass is going to be NSObject.
Inside the braces below the class name, is the object’s “Instance variables” or private data for all you c++ fans out there. A node has link to another node, and a value that it stores. This class will be inhereted from my stack example I’ll show later
Functions:
The class is defined or “implemented” in an m file. Where m stands fro iMplimentation
Note that I imported node.h, but did not have to import cocoa
The primary aspect Obj-C derived from smalltalk was the messaging system. At runtime, a message (which could be a function) is sent to an object and it does what that message says. This is what Dynamic Binding is.
The syntax consists of 2 words in BRACKets usually the Identifier which represents an object or class, and a message to be a method or a “function” to you C++ enthusiasts out there.
Use animation here to help show each comparison at a time
A good way to implement DT, is to use generic identifers like this type id. Id work like pointers to objects. A good example, of how ids work, as written by Cox in his book.
For my example, here link list inherets from Node, such that I can use node specific functions in the code without calling for Node explicitly.
And Stack inherets from Linklist, and All I need to to wrap push and pop around LL functions. What I forgot to mention is that the word self is one of the few built-in words that reference the object itself like C++’s “this” keyword.
Note that I only needed to import “stack.h” and nothing else becaue stack imports LinkList.h which imports Node.h which imports cocoa.h
In this example I make a little stack I push 1 and 2 and pop once and push 3 and pop twice, so I should get 2 3 1 in that order.
I run it in GCC (on MAC OS 10.4 mind you) and get just that.