2012年5月17日 星期四

objectC Class


參考

https://developer.apple.com/library/ios/#referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/_index.html




Strongly typed variables include the class name in the variable type declaration. Weakly typed variables use the type id for the object instead. Weakly typed variables are used frequently for things such as collection classes, where the exact type of the objects in a collection may be unknown


MyClass *myObject1; // Strong typing
id myObject2; // Weak typing


The Objective-C programming language has the following particular syntax for ap-
plying methods to classes and instances:
[ ClassOrInstance method ]; 




從書上剪下的例子 (Addison Wesley - Programming.in.ObjectiveC.2.0.2nd (2009))
#import <Foundation/Foundation.h>
//---- @interface section ----
@interface Fraction: NSObject
{
int  numerator;
int  denominator;
}
-(void)   print;
-(void)   setNumerator: (int) n;
-(void)   setDenominator: (int) d;
@end

//---- @implementation section ----
@implementation Fraction
-(void) print
{
NSLog (@ ” %i/%i ” , numerator, denominator);
}
-(void) setNumerator: (int) n
{
numerator = n;
}
-(void) setDenominator: (int) d
{
denominator = d;
}

@end
//---- program section ----
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction  *myFraction;
// Create an instance of a Fraction
myFraction = [Fraction alloc];
myFraction = [myFraction init];
// 以上三行等效於==>  Fraction *myFraction = [[Fraction alloc] init];
// Set fraction to 1/3
[myFraction setNumerator: 1];
[myFraction setDenominator: 3];
// Display the fraction using the print method
NSLog (@ ” The value of myFraction is: ” );
[myFraction print];
[myFraction release];
[pool drain];
return 0;
}

沒有留言: