Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Chapter 4 briefly touched on the id data type and noted that it is a generic object type. That is, id can be used for storing objects that belong to any class. The real power of this data type is exploited when it’s used this way to store different types of objects in a variable during the execution of a program. Study Program 9.2 and its associated output.
|
Code View:
Scroll
/
Show All // Illustrate Dynamic Typing and Binding
#import "Fraction.h"
#import "Complex.h"
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
id dataValue;
Fraction *f1 = [[Fraction alloc] init];
Complex *c1 = [[Complex alloc] init];
[f1 setTo: 2 over: 5];
[c1 setReal: 10.0 andImaginary: 2.5];
// first dataValue gets a fraction
dataValue = f1;
[dataValue print];
// now dataValue gets a complex number
dataValue = c1;
[dataValue print];
[c1 release];
[f1 release];
[pool drain];
return 0;
}
|