objective-c简陋学习-源码笔记

本文是学习http://www.otierney.net/objective-c.html.zh-tw.big5时的一些代码。

Fraction.h
#import <Foundation/NSObject.h>


@interface  Fraction:NSObject {
    int numerator;
    int denominator;
}
-(Fraction*) initWithNumerator:(int) n denominator:(int) d;
-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;
-(void) setNumerator:(int)n andDenominator: (int)d;
//-(void) setNumerator:(int)n : (int)d;
-(int) numerator;
-(int) denominator;
@end 


Fraction.m
#import "Fraction.h"
#import <stdio.h>

@implementation Fraction

-(Fraction*) initWithNumerator:(int) n denominator:(int) d{
    self = [super init];

    if(self){
	[self setNumerator: n andDenominator: d];
    }
}
-(void) print{
    printf("%i/%i", numerator, denominator);
}

-(void) setNumerator: (int) n {
    numerator = n;
}

-(void) setDenominator: (int) d {
    denominator = d;
}

-(void) setNumerator:(int)n andDenominator: (int)d{
    numerator = n;
    denominator = d;
}
// -(void) setNumerator:(int)n: (int)d{
//     numerator = n;
//     denominator = d;
// }

-(int) denominator{
    return denominator;
}

-(int) numerator{
    return numerator;
}
@end 

@interface  Fraction(Private)
-(void) privateMethod;
@end 
@implementation Fraction(Private)
-(void) privateMethod{
    printf("-----privateMethdo\n");
}
@end 


#if 0
#import <stdio.h>
#import "Fraction.h"


int main(int argc, char **argv) {
    Fraction *frac = [[Fraction alloc] init];
    Fraction *frac2 = [[Fraction alloc] init];
    Fraction *frac3 = [[Fraction alloc] initWithNumerator: 3 denominator: 10];
    
    
    [frac setNumerator: 1];
    [frac setDenominator: 3];
    
    [frac2 setNumerator: 1 andDenominator: 5];

    printf("The fraction is :");
    [frac print];
    printf ("\n");
    
    printf("The fraction2 is :");
    [frac2 print];
    printf ("\n");

    printf("The fraction3 is :");
    [frac3 print];
    printf ("\n");
    
    [frac release];

    return 0;
}
#endif
////////////////////////////////////////////////////////////////////////
#if 0
#import <Foundation/NSObject.h>

@interface  Access:NSObject{
@public 
    int publicVar;
@private 
    int privateVar;
    int privateVar2;
@protected 
    int protectedVar;
}
@end 

@implementation Access
@end 

int main(){
    Access *a = [[Access alloc] init];
    
    a->publicVar = 5;
    printf("public var: %i\n", a->publicVar);
    
    //a->protectedVar = 1;
    
    [a release];
    return 0;
}
#endif
///////////////////////////////////////////////////////////////////////
#if 0
#import <Foundation/NSObject.h>
//#import <Foundation/Foundation.h>

static int count;

@interface  ClassA: NSObject
+(int) initCount;
+(void) initialize;
@end 

@implementation ClassA
-(id) init{
    printf("ClassA init\n");
    self = [super init];
    count++;
    return self;
}
+(int) initCount{
    printf("ClassA initCount\n");
    return count;
}
+(void) initialize{
    printf("ClassA initialize\n");
    count = 0;
}
@end 

int main(){
    ClassA *class1 = [[ClassA alloc] init];
    ClassA *class2 = [[ClassA alloc] init];
    
    printf("ClassA count=%i\n", [ClassA initCount]);
    
    ClassA *class3 = [[ClassA alloc] init];
    
    printf("ClassA count = %i \n", [ClassA initCount]);
//     printf("class1 count = %i \n", [class1 initCount]);
//     printf("class2 count = %i \n", [class2 initCount]);
//     printf("class3 count = %i \n", [class3 initCount]);
//      NSLog(@"hello");
    [class1 release];
    [class2 release];
    [class3 release];
    return 0;
}
#endif
////////////////////////////////////////
//异常处理
#if 0
#import <Foundation/NSException.h>
#import <Foundation/NSObject.h>
#import <Foundation/NSAutoreleasePool.h>

@interface  CupWarningException:NSException
@end 

@implementation CupWarningException
@end 

@interface  CupOverflowException:NSException
@end 

@implementation CupOverflowException
@end 

@interface  Cup: NSObject{
    int level;
}

-(int) level;
-(void) setLevel: (int) l;
-(void) fill;
-(void) empty;
-(void) print;
@end 

@implementation Cup
-(id) init{
    self = [super init];
    if(self){
	[self setLevel: 0];
    }
    return self;
}

-(int) level{
    return level;
}

-(void) setLevel:(int) l{
    level = l;
    NSLog(@"setLevel in : %d", l);
    if(level > 100){
	// throw overflow
	NSException *e = [CupOverflowException
	    exceptionWithName: @"CupOverflowException"
	    reason: @"The level is > 100"
	    userInfo: nil
	];
	@throw e;
    }else if(level >= 50){
	NSException *e = [CupWarningException
	    exceptionWithName: @"CupWarningException"
	    reason: @"The level is >= 50"
	    userInfo: nil
	];
	@throw e;
    }else if(level < 0){
	NSException *e = [NSException
	    exceptionWithName: @"NSException"
	    reason: @"The level is < 0"
	    userInfo: nil
	];
	@throw e;
    }
    NSLog(@"setLevel out : %d", l);
}

-(void) fill{
    [self setLevel: level + 10];
}

-(void) empty{
    [self setLevel: level - 10];
}

-(void) print{
    NSLog(@"Cup level is :%i\n", level);
}
@end 
#include <stdio.h>

int main(){
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    Cup *cup = [[Cup alloc] init];
    int i;
    
    for(i = 0; i < 4; i++){
	[cup fill];
	[cup print];
    }
    
    for(i = 0; i < 7; i++){
	@try{
	    [cup fill];
	}@catch(CupWarningException *e){	    
	    NSLog(@"e name:%s", [[e name] cString]);
	}@catch(CupOverflowException *e){
	    NSLog(@"e name:%s", [[e name] cString]);
	}@finally{ // 保证这里会执行
	    [cup print];
	}
    }
    
    @try{
	[cup setLevel: -1];
#if 1
     }@catch (NSException *e){
 	NSLog(@"%s:%s\n", [[e name] cString], [[e reason] cString]);
     }
#else
    }@catch (id e){ // 这里可以直接用id
	NSLog(@"?????%s:%s\n", [[e name] cString], [[e reason] cString]);
    }
#endif

    [cup release];    
    [pool release];    
    return 0;
}
#endif
/* 输出结果
2012-06-21 02:02:06.691 main[7510] setLevel in : 0
2012-06-21 02:02:06.692 main[7510] setLevel out : 0
2012-06-21 02:02:06.692 main[7510] setLevel in : 10
2012-06-21 02:02:06.692 main[7510] setLevel out : 10
2012-06-21 02:02:06.692 main[7510] Cup level is :10
2012-06-21 02:02:06.692 main[7510] setLevel in : 20
2012-06-21 02:02:06.692 main[7510] setLevel out : 20
2012-06-21 02:02:06.692 main[7510] Cup level is :20
2012-06-21 02:02:06.692 main[7510] setLevel in : 30
2012-06-21 02:02:06.692 main[7510] setLevel out : 30
2012-06-21 02:02:06.692 main[7510] Cup level is :30
2012-06-21 02:02:06.692 main[7510] setLevel in : 40
2012-06-21 02:02:06.692 main[7510] setLevel out : 40
2012-06-21 02:02:06.692 main[7510] Cup level is :40
2012-06-21 02:02:06.692 main[7510] setLevel in : 50
2012-06-21 02:02:06.692 main[7510] e name:CupWarningException
2012-06-21 02:02:06.693 main[7510] Cup level is :50
2012-06-21 02:02:06.693 main[7510] setLevel in : 60
2012-06-21 02:02:06.693 main[7510] e name:CupWarningException
2012-06-21 02:02:06.693 main[7510] Cup level is :60
2012-06-21 02:02:06.693 main[7510] setLevel in : 70
2012-06-21 02:02:06.693 main[7510] e name:CupWarningException
2012-06-21 02:02:06.693 main[7510] Cup level is :70
2012-06-21 02:02:06.693 main[7510] setLevel in : 80
2012-06-21 02:02:06.693 main[7510] e name:CupWarningException
2012-06-21 02:02:06.693 main[7510] Cup level is :80
2012-06-21 02:02:06.693 main[7510] setLevel in : 90
2012-06-21 02:02:06.693 main[7510] e name:CupWarningException
2012-06-21 02:02:06.693 main[7510] Cup level is :90
2012-06-21 02:02:06.693 main[7510] setLevel in : 100
2012-06-21 02:02:06.693 main[7510] e name:CupWarningException
2012-06-21 02:02:06.693 main[7510] Cup level is :100
2012-06-21 02:02:06.693 main[7510] setLevel in : 110
2012-06-21 02:02:06.693 main[7510] e name:CupOverflowException
2012-06-21 02:02:06.693 main[7510] Cup level is :110
2012-06-21 02:02:06.693 main[7510] setLevel in : -1
2012-06-21 02:02:06.693 main[7510] NSException:The level is < 0

 */


////////////////////////////////////////////////////////////////////////////////////////////////
// 继承 (Inheritance)
#if 0
#import <Foundation/NSObject.h>
#import <Foundation/Foundation.h>

@interface  Rectangle: NSObject{
    int width;
    int height;
}
#if 1
-(Rectangle*) initWithWidth: (int) w height: (int) h;
#else
-(id) initWithWidth: (int) w height: (int) h;
#endif
-(void) setWidth: (int) w;
-(void) setHeight: (int) h;
-(void) setWidth: (int) w height: (int) h;
-(int) widht;
-(int) height;
-(void) print;
@end 

@implementation Rectangle
#if 1
-(Rectangle*) initWithWidth: (int) w height: (int) h{
#else
-(id) initWithWidth: (int) w height: (int) h{
#endif
    self = [super init];
    if(self){
	[self setWidth:w height: h];
    }
    return self;
}

-(void) setWidth: (int) w{
    width = w;
}

-(void) setHeight: (int) h{
    height = h;
}

-(void) setWidth: (int) w height: (int) h{
    width = w;
    height = h;
}

-(int) widht{
    return width;
}

-(int) height{
    return height;
}

-(void) print{
    NSLog(@"width = %i, height = %i", width, height);
}
@end 

// 子类 Square
@interface  Square: Rectangle
-(Square*) initWithSize: (int) s;
-(void) setSize: (int) s;
-(int) size;
@end 

@implementation Square
-(Square*) initWithSize: (int) s{
    self = [super init];
    if(self){
	[self setSize: s];
    }
    return self;
}

-(void) setSize: (int) s{
    width = s;
    height = s;
}

-(int) size{
    return width;
}

-(void) setWidth: (int) w{
    [self setSize: w];
}

-(void) setHeight: (int) h{
    [self setSize: h];
}
@end 

int main(){
    Rectangle *rec = [[Rectangle alloc] initWithWidth: 10 height: 20];
#if 1
    Square *sq = [[Square alloc] initWithSize: 15];
#else
    // 如果Rectangle中的initWithWidth申明为返回Rectangle,那么这行代码会有警告,但运行结果正确???
    //main.m:376:5: warning: initialization from distinct Objective-C type [enabled by default]

    Square *sq = [[Square alloc] initWithWidth: 25 height: 25];
#endif
    printf("Rectangle:");
    [rec print];
    printf("\n");
    
    printf("Square: ");
    [sq print];
    printf("\n");
    
    //update
    [sq setWidth: 20];
    printf("Square after change:");
    [sq print];
    printf("\n");
    
    NSLog(@"%@", [rec class]);//返回rec的类名
    //NSLog(@"%@", [sq isKindOfClass: [rec class]]);//段错误
       
    if([sq isMemberOfClass:[Square class]] == YES){
	printf("sq is member of square class\n");
    }
    
    if([sq isMemberOfClass: [Rectangle class]] == YES){
	printf("sq is member of rectangel class\n");
    }
    
    if([sq isMemberOfClass:[NSObject class]] == YES){
	printf("sq is member of NSObject class\n");
    }
    
    if([sq isKindOfClass:[Square class]] == YES){
	printf("sq is kind of square class\n");
    }
    
    if([sq isKindOfClass: [Rectangle class]] == YES){
	printf("sq is kind of rectangel class\n");
    }
    
    if([sq isKindOfClass:[NSObject class]] == YES){
	printf("sq is kind of NSObject class\n");
    }
    
    //respondsToSelector
    
    //true
    if([sq respondsToSelector: @selector(setSize:)] == YES){
	printf("sq responds to setSize: method\n");
    }
    //false
    if([sq respondsToSelector: @selector(nonExistant)] == YES){
	printf("sq responds to nonExistant method\n");
    }
    //true
    if([Square respondsToSelector: @selector(alloc)] == YES){
	printf("square class responds to alloc method\n");
    }
    
    //instancesRespondToSelector
    
    //false
    if([Rectangle instancesRespondToSelector: @selector(setSize:)] == YES){
	printf("rectangle instance responds to setSize: method\n");
    }
    //true
    if([Square instancesRespondToSelector: @selector(setSize:)] == YES){
	printf("square instance responds to setSize: method\n");
    }
    
    
    [sq release];
    [rec release];
    return 0;
}

/* 结果如下,为什么NSLog打印的内容会比printf要快呢??????
2012-06-21 02:37:30.160 main[8451] width = 10, height = 20
Rectangle:
2012-06-21 02:37:30.161 main[8451] width = 15, height = 15
Square: 
2012-06-21 02:37:30.161 main[8451] width = 20, height = 20
Square after change:

sq is member of square class
sq is kind of square class
sq is kind of rectangel class
sq is kind of NSObject class
sq responds to setSize: method
square class responds to alloc method
square instance responds to setSize: method

 */
#endif

/////////////////////////////////////////////////////////////////
// Categories
// 扩展类:可以在原类基础上扩展接口,不用继承的方法重写类
// 重点是@implemention 跟@interface  这两行:
// 类名后加入了(Math)。
// 同一个class只能有一个同名的category,其他的categories的加上不同的独一无二的名字。

#if 0
#import "Fraction.h"

@interface  Fraction(Math)
-(Fraction*) add: (Fraction*) f;
-(Fraction*) mul: (Fraction*) f;
//-(Fraction*) div: (Fraction*) f;
//-(Fraction*) sub: (Fraction*) f;
@end 

@implementation Fraction(Math)
-(Fraction*) add: (Fraction*) f{
    return [[Fraction alloc] initWithNumerator:
	numerator * [f denominator] + denominator * [f numerator]
			    denominator:
	denominator * [f denominator]
			    
    ];
    
}

-(Fraction*) mul: (Fraction*) f{
    return [[Fraction alloc] initWithNumerator:
	numerator * [f numerator]
			    denominator:
	denominator * [f denominator]
	
    ];
}
@end 

int main(){
    Fraction *frac1 = [[Fraction alloc] initWithNumerator: 1 denominator: 3];
    Fraction *frac2 = [[Fraction alloc] initWithNumerator: 2 denominator: 5];
    Fraction *frac3 = [frac1 mul: frac2];
    
    [frac1 print];
    printf(" * ");
    [frac2 print];
    printf(" = ");
    [frac3 print];
    printf(" \n");
    
    [frac1 privateMethod];
    [frac2 privateMethod];
    [frac3 privateMethod];
    
    [frac1 release];
    [frac2 release];
    [frac3 release];
    return 0;
}
/*
result
1/3 * 2/5 = 2/15 
*/
#endif

//////////////////////////////////////////////////////////////////////////
// Posing 
// 有点像categories, 但是又不太一样,它允许你扩充一个class, 并且全面性的扮演(pose)
// 这个super class
// 例如:有一个扩充NSArray的NSArrayChild,如果你让NSArrayChild扮演NSArray, 则在你的
// 程序代码中,所有的NSArray都会自动替换为NSArrayChild。
#if 0
#import "Fraction.h"

@interface  FractionB: Fraction
-(void) print;
@end 

@implementation FractionB
-(void) print{
    printf("(%i/%i)", numerator, denominator);
}
@end 


int main(){
    Fraction *frac = [[Fraction alloc] initWithNumerator: 3 denominator: 10];
    
    //print it
    printf("The fraction is: ");
    [frac print];
    printf("\n");
    
    //./main: Uncaught exception NSInternalInconsistencyException, 
    // reason: Class posing is not supported
    // 下面这句话在GNUstep中运行时会报错,
    [FractionB poseAsClass: [Fraction class]];
    
    Fraction *frac2 = [[Fraction alloc] initWithNumerator: 3 denominator: 10];
    
    //print it
    printf("The fraction is: ");
    [frac2 print];
    printf("\n");
    
    //print it
    printf("The fraction is: ");
    [frac print];
    printf("\n");
    
    [frac2 release];
    [frac release];
    return 0;
}

#endif

////////////////////////////////////////////////////////////////////////////////////
// Protocols
// 和c++中的purely irtual class 纯虚函数相同
#if 0

#import <Foundation/NSObject.h>

@interface  Fraction: NSObject<Printing, NSCopying>{
    int numerator;
    int denominator;
}

@end 
@implementation Fraction
@end 

//可以使用 id<Printing> var = frac;

#endif

////////////////////////////////////////////////////////////////////////////////////
// 内存管理
// Retain和release是两个继承自NSObject的对象都会有的methods。
// retain call 增加计数器值, 而release call减少它。
// 使用[obj retainCount]取得计数器个数
// 当retainCount个数达到0, 会dealloc自己
#if 0
#import <Foundation/NSObject.h>


@interface  FractionEx:NSObject {
    int numerator;
    int denominator;
}

@end 

@implementation FractionEx
-(void) dealloc{
    printf("Deallocing fraction\n");
    [super dealloc];
}
@end 

int main(){
    FractionEx *frac1 = [[FractionEx alloc ] init];
    FractionEx *frac2 = [[FractionEx alloc ] init];
 
    printf("FractionEx 1 retain count: %i\n", [frac1 retainCount]);//1
    printf("FractionEx 2 retain count: %i\n", [frac2 retainCount]);//1
    
    printf("frac1 retain\n");
    [frac1 retain];//2
    printf("frac1 retain\n");
    [frac1 retain];//3
    printf("frac2 retain\n");
    [frac2 retain];//2
    
    printf("FractionEx 1 retain count: %i\n", [frac1 retainCount]);
    printf("FractionEx 2 retain count: %i\n", [frac2 retainCount]);
    
    printf("frac1 release\n");
    [frac1 release];//2
    printf("FractionEx 1 retain count: %i\n", [frac1 retainCount]);
    printf("FractionEx 2 retain count: %i\n", [frac2 retainCount]);
    printf("frac2 release\n");
    [frac2 release];//1
    
    printf("FractionEx 1 retain count: %i\n", [frac1 retainCount]);
    printf("FractionEx 2 retain count: %i\n", [frac2 retainCount]);
    
    printf("frac1 retain\n");
    [frac1 release];//1
    printf("frac1 retain\n");
    [frac1 release];//0
    printf("frac2 retain\n");
    [frac2 release];//0
    
    return 0;
}

#endif

////////////////////////////////////////////////////////////////////////////////////
// Dealloc
// 当你的对象包含其他对象时,就得在dealloc中自行释放。
// objective-c的一个优点是可以传递nil,所以不需要经过一堆防错测试来释放一个对象
#if 0
#import <Foundation/NSObject.h>
#import <Foundation/NSString.h>

@interface  AddressCard: NSObject{
    NSString *first;
    NSString *last;
    NSString *email;
}
-(AddressCard*) initWithFirst:(NSString*) f
		last: (NSString*) l
		email: (NSString*) e;
-(NSString*) first;
-(NSString*) last;
-(NSString*) email;
-(void) setFirst:(NSString*) f;
-(void) setLast:(NSString*) l;
-(void) setEmail:(NSString*) e;
-(void) setFirst:(NSString*) f
	last:(NSString*) l
	email:(NSString*) e;
-(void) setFirst:(NSString*) f
	last:(NSString*) l;
-(void) print;
@end 

@implementation AddressCard
-(AddressCard*) initWithFirst:(NSString*) f
		last: (NSString*) l
		email: (NSString*) e{
    self = [super init];
    if(self){
	[self setFirst:f last: l email: e];
    }
}
-(NSString*) first{
    return first;
}
-(NSString*) last{
    return last;
}
-(NSString*) email{
    return email;
}
-(void) setFirst:(NSString*) f{
    [f retain];//这里去掉会出现段错误
    [first release];
    first = f;
}
-(void) setLast:(NSString*) l{
    [l retain];
    [last release];
    last = l;
}
-(void) setEmail:(NSString*) e{
    [e retain];
    [email release];
    email = e;
}
-(void) setFirst:(NSString*) f
	last:(NSString*) l
	email:(NSString*) e{
    [self setFirst: f];
    [self setLast: l];
    [self setEmail: e];
}
-(void) setFirst:(NSString*) f
	last:(NSString*) l{
    [self setFirst: f];
    [self setLast: l]; 
}
-(void) print{
    printf("%s %s <%s>", [first cString], [last cString], [email cString]);
    printf("\nclass first retaincount:%i", [first retainCount]);
    printf("\nclass last retaincount:%i", [last retainCount]);
    printf("\nclass email retaincount:%i", [email retainCount]);
}

-(void) dealloc{
    [first release];
    [last release];
    [email release];
    
    [super dealloc];
}
@end 

int main(){
    NSString *first = [[NSString alloc] initWithCString: "Zhao"];
    NSString *last = [[NSString alloc] initWithCString: "Kun"];
    NSString *email = [[NSString alloc] initWithCString: "[email protected]"];
    
    AddressCard *zhao = [[AddressCard alloc] initWithFirst: first
					    last: last
					    email: email
			];
    
    [first release];
    [last release];
    [email release];
    
    printf("zhao first Retain count: %i\n", [[zhao first] retainCount]);
    printf("zhao last Retain count: %i\n", [[zhao last] retainCount]);
    printf("zhao email Retain count: %i\n", [[zhao email] retainCount]);
    
    [zhao print];
    printf("\n");
    
    [zhao release];
    
    return 0;
}
/*
zhao first Retain count: 1
zhao last Retain count: 1
zhao email Retain count: 1
2012-06-22 15:03:31.059 main[4257] autorelease called without pool for object (0x9195a10) of class GSAutoreleasedMemory in thread <NSThread: 0x91675d8>
2012-06-22 15:03:31.060 main[4257] autorelease called without pool for object (0x9196068) of class GSAutoreleasedMemory in thread <NSThread: 0x91675d8>
2012-06-22 15:03:31.060 main[4257] autorelease called without pool for object (0x9195848) of class GSAutoreleasedMemory in thread <NSThread: 0x91675d8>
Zhao Kun <[email protected]>
class first retaincount:1
class last retaincount:1
class email retaincount:1

 */
#endif

//////////////////////////////////////////////////////////////////////////////////
// Autorelease pool
// 在objective-c有两种管理内存的方法:
// 1.retain 和 release
// 2.retain 和release/autorelease
// 对于每个retain, 一定对应一个release或一个autorelease
#if 1
#import <Foundation/NSString.h>
#import <Foundation/NSAutoreleasePool.h>
#if 0
int main(){
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString *str1 = @"constant string";
    NSString *str2 = [NSString stringWithString: @"string managed by the pool"];
    NSString *str3 = [[NSString alloc] initWithString: @"self managed string"];
    
    printf("%s retain count: %x\n", [str1 cString], [str1 retainCount]);
    printf("%s retain count: %x\n", [str2 cString], [str2 retainCount]);
    printf("%s retain count: %x\n", [str3 cString], [str3 retainCount]);
    
    [str3 release];
    
    [pool release];
}
/*
constant string retain count: 343b
string managed by the pool retain count: 1
self managed string retain count: 1

执行这个程序会发现几个问题:
1.str1的retainCount为343b
2.虽然只有release str3, 但是整个程序却还是处于完美的内存管理下,
原因是第一个常数字符串已经自动加到autorelease pool里了。
字符串是由stringWithString产生的, 这个接口会产生一个NSString class类型的字符串,并自动
加进autorelease pool中。
*/
#endif
#if 0

// 对任何retain而言,一定要调用release或autorelease, 对象的retainCount从1起跳,然后我在
// 上面调用1次autorelease,表示1-1=0, 当autorelease pool被释放时, 它会计算所有对象上的
// autorealease调用次数, 并调用相同次数的[obj release];
#import "Fraction.h"

@interface  Fraction(Ex)
+(Fraction*) fractionWithNumerator: (int) n
		denominator: (int) d; 
@end 
@implementation Fraction(Ex)
+(Fraction*) fractionWithNumerator: (int) n
		denominator: (int) d{
    Fraction *ret = [[Fraction alloc] initWithNumerator: n denominator: d];
    [ret autorelease];
    return ret;
}
@end 

int main(){
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    Fraction *frac1 = [Fraction fractionWithNumerator:2 denominator: 5];
    Fraction *frac2 = [Fraction fractionWithNumerator: 1 denominator: 3];
    
    printf("Fraction 1: ");
    [frac1 print];
    printf("\n");
    
    printf("Fraction 2: ");
    [frac2 print];
    printf("\n");
    
    //下面这句话会出现段错误
    //[frac1 release];
    
    [pool release];
    return 0;    
}
#endif
#endif

//////////////////////////////////////////////////////////////////////////////////
// NSArray
// 数组有两种,NSArray和NSMutableArray,
// NSArray不能改变长度,NSMutableArray可以改变
// NSEnumerator很想java的列举系统,
#if 0
#import <Foundation/NSArray.h>
#import <Foundation/NSString.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSEnumerator.h>

void print(NSArray *array){
    NSEnumerator *enumerator = [array objectEnumerator];
    id obj;
    while(obj = [enumerator nextObject]){
	printf("%s\n", [[obj description] cString]);
    }
}

int main(){
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSArray *arr = [[NSArray alloc] initWithObjects: @"Me", @"Myself", @"I", nil];
    NSMutableArray *mutable = [[NSMutableArray alloc] init];
    
    printf("----static array\n");
    print(arr);
    
    // add stuff
    [mutable addObject: @"One"];
    [mutable addObject: @"Two"];
    [mutable addObjectsFromArray: arr];
    [mutable addObject: @"Three"];
    
    printf("----mutable array\n");
    print(mutable);
    
    //sort
    printf("----sorted mutable array\n");
    [mutable sortUsingSelector: @selector(caseInsensitiveCompare:)];
    print(mutable);
    
    //free
    [arr release];
    [mutable release];
    
    [pool release];
    return 0;
}
/*
----static array
Me
Myself
I
----mutable array
One
Two
Me
Myself
I
Three
----sorted mutable array
I
Me
Myself
One
Three
Two

*/
#endif

//////////////////////////////////////////////////////////////////////////////////
// NSDictionary

#if 1
#import <Foundation/NSString.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSEnumerator.h>
#import <Foundation/Foundation.h>

void print(NSDictionary *map){
    NSEnumerator *enumerator = [map keyEnumerator];
    id key;
    
    while((key = [enumerator nextObject]) != nil){
	printf("%s => %s\n", [[key description] cString]
			    , [[[map objectForKey: key] description] cString]);
    }
}

int main(){
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
	@"one", [NSNumber numberWithInt: 1],
	@"two", [NSNumber numberWithInt: 2],
	@"three", [NSNumber numberWithInt: 3],
	nil];
    NSMutableDictionary *mutable = [[NSMutableDictionary alloc] init];
    
    printf("----static dictionary\n");
    print(dict);
    
    //add object
    [mutable setObject: @"Tom" forKey: @"[email protected]"];
    [mutable setObject: @"Bob" forKey: @"[email protected]"];
    
    printf("----mutable dictionary\n");
    print(mutable);
    
    //free
    [dict release];
    [mutable release];
    
    [pool release];
}
/*
----static dictionary
3 => three
1 => one
2 => two
----mutable dictionary
[email protected] => Bob
[email protected] => Tom

 */
#endif


你可能感兴趣的:(Objective-C,obj-c,objC)