ios应用开发Objective-C代码

时间:2012-02-15关注公众号来源:51cto

目录:

   第 1 页:设定环境

   第 2 页:创建 Classes

   第 3 页:详细说明

   第 4 页:继承、多型(Inheritance, Polymorphism)以及其他物件导向功能

   第 8 页:记忆体管理

   第 9 页:Foundation Framework Classes

  所有这篇初学者指南的塬始码都可以由 objc.tar.gz 下载。这篇教学中的许多範例都是由 Steve Kochan 在 Programming in Objective-C. 一书中撰写。如果你想得到更多详细资讯及範例,请直接参考该书。这个网站上登载的所有範例皆经过他的允许,所以请勿复製转载。

  设定环境

  Linux/FreeBSD: 安装 GNUStep

  为了编译 GNUstep 应用程式,必须先执行位于 /usr/GNUstep/System/Makefiles/GNUstep.sh 的 GNUstep.sh 这个档案。这个路径取决于你的系统环境,有些是在 /usr, some /usr/lib,有些是 /usr/local。如果你的 shell 是以 csh/tcsh 为基础的 shell,则应该改用 GNUStep.csh。建议把这个指令放在 .bashrc 或 .cshrc 中。

  Mac OS X: 安装 XCode

  Windows NT 5.X: 安装 cygwin 或 mingw,然后安装 GNUStep

  前言

  这篇教学假设你已经有一些基本的 C 语言知识,包括 C 资料型别、什么是函式、什么是回传值、关于指标的知识以及基本的 C 语言记忆体管理。如果您没有这些背景知识,我非常建议你读一读 K&R 的书:The C Programming Language(译注:台湾出版书名为 C 程式语言第二版)这是 C 语言的设计者所写的书。

  Objective-C,是 C 的衍生语言,继承了所有 C 语言的特性。是有一些例外,但是它们不是继承于 C 的语言特性本身。

  nil:在 C/C++ 你或许曾使用过 NULL,而在 Objective-C 中则是 nil。不同之处是你可以传递讯息给 nil(例如 [nil message];),这是完全合法的,然而你却不能对 NULL 如法炮製。

  BOOL:C 没有正式的布林型别,而在 Objective-C 中也不是「真的」有。它是包含在 Foundation classes(基本类别库)中(即 import NSObject.h;nil 也是包括在这个标头档内)。BOOL 在 Objective-C 中有两种型态:YES 或 NO,而不是 TRUE 或 FALSE。

  #import vs #include:就如同你在 hello world 範例中看到的,我们使用了 #import。#import 由 gcc 编译器支援。我并不建议使用 #include,#import 基本上跟 .h 档头尾的 #ifndef #define #endif 相同。许多程式员们都同意,使用这些东西这是十分愚蠢的。无论如何,使用 #import 就对了。这样不但可以避免麻烦,而且万一有一天 gcc 把它拿掉了,将会有足够的 Objective-C 程式员可以坚持保留它或是将它放回来。偷偷告诉你,Apple 在它们官方的程式码中也使用了 #import。所以万一有一天这种事真的发生,不难预料 Apple 将会提供一个支援 #import 的 gcc 分支版本。

  在 Objective-C 中, method 及 message 这两个字是可以互换的。不过 messages 拥有特别的特性,一个 message 可以动态的转送给另一个物件。在 Objective-C 中,唿叫物件上的一个讯息并不一定表示物件真的会实作这个讯息,而是物件知道如何以某种方式去实作它,或是转送给知道如何实作的物件。

  编译 hello world

  1. hello.m 
  2.  
  3. #import 
  4.  
  5. int main( int argc, const char *argv[] ) { 
  6.  
  7. printf( "hello world " ); 
  8.  
  9. return 0; 
  10.  
  11. } 
  12.  

  输出

helloworld

在Objective-C中使用#import代替#include

Objective-C的预设副档名是.m

  


  创建classes

@interface

  1.   
  2.   
  3. Fraction.h  
  4.   
  5. #import  
  6.   
  7. @interface Fraction: NSObject {  
  8.   
  9. int numerator;  
  10.   
  11. int denominator;  
  12.   
  13. }  
  14.   
  15. -(void) print;  
  16.   
  17. -(void) setNumerator: (int) n;  
  18.   
  19. -(void) setDenominator: (int) d;  
  20.   
  21. -(int) numerator;  
  22.   
  23. -(int) denominator;  
  24.   
  25. @end  

  NSObject:NeXTStep Object 的缩写。因为它已经改名为 OpenStep,所以这在今天已经不是那么有意义了。

  继承(inheritance)以 Class: Parent 表示,就像上面的 Fraction: NSObject。

  夹在 @interface Class: Parent { .... } 中的称为 instance variables。

  没有设定存取权限(protected, public, private)时,预设的存取权限为 protected。设定权限的方式将在稍后说明。

  Instance methods 跟在成员变数(即 instance variables)后。格式为:scope (returnType) methodName: (parameter1Type) parameter1Name;

  scope 有class 或 instance 两种。instance methods 以 - 开头,class level methods 以 + 开头。

  Interface 以一个 @end 作为结束。

  @implementation

  1. Fraction.m 
  2.  
  3. #import "Fraction.h" 
  4.  
  5. #import 
  6.  
  7. @implementation Fraction 
  8.  
  9. -(void) print { 
  10.  
  11. printf( "%i/%i", numerator, denominator ); 
  12.  
  13. } 
  14.  
  15. -(void) setNumerator: (int) n { 
  16.  
  17. nnumerator = n; 
  18.  
  19. } 
  20.  
  21. -(void) setDenominator: (int) d { 
  22.  
  23. ddenominator = d; 
  24.  
  25. } 
  26.  
  27. -(int) denominator { 
  28.  
  29. return denominator; 
  30.  
  31. } 
  32.  
  33. -(int) numerator { 
  34.  
  35. return numerator; 
  36.  
  37. } 
  38.  
  39. @end 

  Implementation 以 @implementation ClassName 开始,以 @end 结束。

  Implement 定义好的 methods 的方式,跟在 interface 中宣告时很近似。

  把它们凑在一起

  1. main.m 
  2.  
  3. #import 
  4.  
  5. #import "Fraction.h" 
  6.  
  7. int main( int argc, const char *argv[] ) { 
  8.  
  9. // create a new instance 
  10.  
  11. Fraction *frac = [[Fraction alloc] init]; 
  12.  
  13. // set the values 
  14.  
  15. [frac setNumerator: 1]; 
  16.  
  17. [frac setDenominator: 3]; 
  18.  
  19. // print it 
  20.  
  21. printf( "The fraction is: " ); 
  22.  
  23. [frac print]; 
  24.  
  25. printf( " " ); 
  26.  
  27. // free memory 
  28.  
  29. [frac release]; 
  30.  
  31. return 0; 
  32.  
  33. } 

  output

  1. The fraction is: 1/3 
  2.  
  3. Fraction *frac = [[Fraction alloc] init]; 

  这行程式码中有很多重要的东西。

  在 Objective-C 中唿叫 methods 的方法是 [object method],就像 C++ 的 object->method()。

  Objective-C 没有 value 型别。所以没有像 C++ 的 Fraction frac; frac.print(); 这类的东西。在 Objective-C 中完全使用指标来处理物件。

  这行程式码实际上做了两件事: [Fraction alloc] 唿叫了 Fraction class 的 alloc method。这就像 malloc 记忆体,这个动作也做了一样的事情。

  [object init] 是一个建构子(constructor)唿叫,负责初始化物件中的所有变数。它唿叫了 [Fraction alloc] 传回的 instance 上的 init method。这个动作非常普遍,所以通常以一行程式完成:Object *var = [[Object alloc] init];

  [frac setNumerator: 1] 非常简单。它唿叫了 frac 上的 setNumerator method 并传入 1 为参数。

  如同每个 C 的变体,Objective-C 也有一个用以释放记忆体的方式: release。它继承自 NSObject,这个 method 在之后会有详尽的解说。

  


  多重参数

  目前为止我还没展示如何传递多个参数。这个语法乍看之下不是很直觉,不过它却是来自一个十分受欢迎的 Smalltalk 版本。

  1. Fraction.h 
  2.  
  3. ... 
  4.  
  5. -(void) setNumerator: (int) n andDenominator: (int) d; 
  6.  
  7. ... 
  8.  
  9. Fraction.m 
  10.  
  11. ... 
  12.  
  13. -(void) setNumerator: (int) n andDenominator: (int) d { 
  14.  
  15. nnumerator = n; 
  16.  
  17. ddenominator = d; 
  18.  
  19. } 
  20.  
  21. ... 
  22.  
  23. main.m 
  24.  
  25. #import 
  26.  
  27. #import "Fraction.h" 
  28.  
  29. int main( int argc, const char *argv[] ) { 
  30.  
  31. // create a new instance 
  32.  
  33. Fraction *frac = [[Fraction alloc] init]; 
  34.  
  35. Fraction *frac2 = [[Fraction alloc] init]; 
  36.  
  37. // set the values 
  38.  
  39. [frac setNumerator: 1]; 
  40.  
  41. [frac setDenominator: 3]; 
  42.  
  43. // combined set 
  44.  
  45. [frac2 setNumerator: 1 andDenominator: 5]; 
  46.  
  47. // print it 
  48.  
  49. printf( "The fraction is: " ); 
  50.  
  51. [frac print]; 
  52.  
  53. printf( " " ); 
  54.  
  55. // print it 
  56.  
  57. printf( "Fraction 2 is: " ); 
  58.  
  59. [frac2 print]; 
  60.  
  61. printf( " " ); 
  62.  
  63. // free memory 
  64.  
  65. [frac release]; 
  66.  
  67. [frac2 release]; 
  68.  
  69. return 0; 
  70.  
  71. } 

  output

  1. The fraction is: 1/3 
  2.  
  3. Fraction 2 is: 1/5 

  这个 method 实际上叫做 setNumerator:andDenominator:

  加入其他参数的方法就跟加入第二个时一样,即 method:label1:label2:label3: ,而唿叫的方法是 [obj method: param1 label1: param2 label2: param3 label3: param4]

  Labels 是非必要的,所以可以有一个像这样的 method:method:::,简单的省略 label 名称,但以 : 区隔参数。并不建议这样使用。

  建构子(Constructors)

  1. Fraction.h 
  2.  
  3. ... 
  4.  
  5. -(Fraction*) initWithNumerator: (int) n denominator: (int) d; 
  6.  
  7. ... 
  8.  
  9. Fraction.m 
  10.  
  11. ... 
  12.  
  13. -(Fraction*) initWithNumerator: (int) n denominator: (int) d { 
  14.  
  15. self = [Super init]; 
  16.  
  17. if ( self ) { 
  18.  
  19. [self setNumerator: n andDenominator: d]; 
  20.  
  21. } 
  22.  
  23. return self; 
  24.  
  25. } 
  26.  
  27. ... 
  28.  
  29. main.m 
  30.  
  31. #import 
  32.  
  33. #import "Fraction.h" 
  34.  
  35. int main( int argc, const char *argv[] ) { 
  36.  
  37. // create a new instance 
  38.  
  39. Fraction *frac = [[Fraction alloc] init]; 
  40.  
  41. Fraction *frac2 = [[Fraction alloc] init]; 
  42.  
  43. Fraction *frac3 = [[Fraction alloc] initWithNumerator: 3 denominator: 10]; 
  44.  
  45. // set the values 
  46.  
  47. [frac setNumerator: 1]; 
  48.  
  49. [frac setDenominator: 3]; 
  50.  
  51. // combined set 
  52.  
  53. [frac2 setNumerator: 1 andDenominator: 5]; 
  54.  
  55. // print it 
  56.  
  57. printf( "The fraction is: " ); 
  58.  
  59. [frac print]; 
  60.  
  61. printf( " " ); 
  62.  
  63. printf( "Fraction 2 is: " ); 
  64.  
  65. [frac2 print]; 
  66.  
  67. printf( " " ); 
  68.  
  69. printf( "Fraction 3 is: " ); 
  70.  
  71. [frac3 print]; 
  72.  
  73. printf( " " ); 
  74.  
  75. // free memory 
  76.  
  77. [frac release]; 
  78.  
  79. [frac2 release]; 
  80.  
  81. [frac3 release]; 
  82.  
  83. return 0; 
  84.  
  85. } 

  output

  1. The fraction is: 1/3 
  2.  
  3. Fraction 2 is: 1/5 
  4.  
  5. Fraction 3 is: 3/10 

  @interface 裡的宣告就如同正常的函式。

  @implementation 使用了一个新的关键字:super

  如同 Java,Objective-C 只有一个 parent class(父类别)。

  使用 [super init] 来存取 Super constructor,这个动作需要适当的继承设计。

  你将这个动作回传的 instance 指派给另一新个关键字:self。Self 很像 C++ 与 Java 的 this 指标。

  if ( self ) 跟 ( self != nil ) 一样,是为了确定 super constructor 成功传回了一个新物件。nil 是 Objective-C 用来表达 C/C++ 中 NULL 的方式,可以引入 NSObject 来取得。

  当你初始化变数以后,你用传回 self 的方式来传回自己的位址。

  预设的建构子是 -(id) init。

  技术上来说,Objective-C 中的建构子就是一个 "init" method,而不像 C++ 与 Java 有特殊的结构。

  存取权限

  预设的权限是 @protected

  Java 实作的方式是在 methods 与变数前面加上 public/private/protected 修饰语,而 Objective-C 的作法则更像 C++ 对于 instance variable(译注:C++ 术语一般称为 data members)的方式。

  1. Access.h 
  2.  
  3. #import 
  4.  
  5. @interface Access: NSObject { 
  6.  
  7. @public 
  8.  
  9. int publicVar; 
  10.  
  11. @private 
  12.  
  13. int privateVar; 
  14.  
  15. int privateVar2; 
  16.  
  17. @protected 
  18.  
  19. int protectedVar; 
  20.  
  21. } 
  22.  
  23. @end 
  24.  
  25. Access.m 
  26.  
  27. #import "Access.h" 
  28.  
  29. @implementation Access 
  30.  
  31. @end 
  32.  
  33. main.m 
  34.  
  35. #import "Access.h" 
  36.  
  37. #import 
  38.  
  39. int main( int argc, const char *argv[] ) { 
  40.  
  41. Access *a = [[Access alloc] init]; 
  42.  
  43. // works 
  44.  
  45. a->publicVar = 5; 
  46.  
  47. printf( "public var: %i ", a->publicVar ); 
  48.  
  49. // doesn't compile 
  50.  
  51. //a->privateVar = 10; 
  52.  
  53. //printf( "private var: %i ", a->privateVar ); 
  54.  
  55. [a release]; 
  56.  
  57. return 0; 
  58.  
  59. } 

  output

  1. public var: 5 

  如同你所看到的,就像 C++ 中 private: [list of vars] public: [list of vars] 的格式,它只是改成了@private, @protected, 等等。

  Class level access

  1. ClassA.h 
  2.  
  3. #import 
  4.  
  5. static int count; 
  6.  
  7. @interface ClassA: NSObject 
  8.  
  9. +(int) initCount; 
  10.  
  11. +(void) initialize; 
  12.  
  13. @end 
  14.  
  15. ClassA.m 
  16.  
  17. #import "ClassA.h" 
  18.  
  19. @implementation ClassA 
  20.  
  21. -(id) init { 
  22.  
  23. self = [super init]; 
  24.  
  25. count++; 
  26.  
  27. return self; 
  28.  
  29. } 
  30.  
  31. +(int) initCount { 
  32.  
  33. return count; 
  34.  
  35. } 
  36.  
  37. +(void) initialize { 
  38.  
  39. count = 0; 
  40.  
  41. } 
  42.  
  43. @end 
  44.  
  45. main.m 
  46.  
  47. #import "ClassA.h" 
  48.  
  49. #import 
  50.  
  51. int main( int argc, const char *argv[] ) { 
  52.  
  53. ClassA *c1 = [[ClassA alloc] init]; 
  54.  
  55. ClassA *c2 = [[ClassA alloc] init]; 
  56.  
  57. // print count 
  58.  
  59. printf( "ClassA count: %i ", [ClassA initCount] ); 
  60.  
  61. ClassA *c3 = [[ClassA alloc] init]; 
  62.  
  63. // print count again 
  64.  
  65. printf( "ClassA count: %i ", [ClassA initCount] ); 
  66.  
  67. [c1 release]; 
  68.  
  69. [c2 release]; 
  70.  
  71. [c3 release]; 
  72.  
  73. return 0; 
  74.  
  75. } 

  output

  1. ClassA count: 2 
  2.  
  3. ClassA count: 3 

  static int count = 0; 这是 class variable 宣告的方式。其实这种变数摆在这裡并不理想,比较好的解法是像 Java 实作 static class variables 的方法。然而,它确实能用。

  +(int) initCount; 这是回传 count 值的实际 method。请注意这细微的差别!这裡在 type 前面不用减号 - 而改用加号 +。加号 + 表示这是一个 class level function。(译注:许多文件中,class level functions 被称为 class functions 或 class method)

  存取这个变数跟存取一般成员变数没有两样,就像 ClassA 中的 count++ 用法。

  +(void) initialize method is 在 Objective-C 开始执行你的程式时被唿叫,而且它也被每个 class 唿叫。这是初始化像我们的 count 这类 class level variables 的好地方。

  异常情况(Exceptions)

  注意:异常处理只有 Mac OS X 10.3 以上才支援。

  1. CupWarningException.h 
  2.  
  3. #import 
  4.  
  5. @interface CupWarningException: NSException 
  6.  
  7. @end 
  8.  
  9. CupWarningException.m 
  10.  
  11. #import "CupWarningException.h" 
  12.  
  13. @implementation CupWarningException 
  14.  
  15. @end 
  16.  
  17. CupOverflowException.h 
  18.  
  19. #import 
  20.  
  21. @interface CupOverflowException: NSException 
  22.  
  23. @end 
  24.  
  25. CupOverflowException.m 
  26.  
  27. #import "CupOverflowException.h" 
  28.  
  29. @implementation CupOverflowException 
  30.  
  31. @end 
  32.  
  33. Cup.h 
  34.  
  35. #import 
  36.  
  37. @interface Cup: NSObject { 
  38.  
  39. int level; 
  40.  
  41. } 
  42.  
  43. -(int) level; 
  44.  
  45. -(void) setLevel: (int) l; 
  46.  
  47. -(void) fill; 
  48.  
  49. -(void) empty; 
  50.  
  51. -(void) print; 
  52.  
  53. @end 
  54.  
  55. Cup.m 
  56.  
  57. #import "Cup.h" 
  58.  
  59. #import "CupOverflowException.h" 
  60.  
  61. #import "CupWarningException.h" 
  62.  
  63. #import 
  64.  
  65. #import 
  66.  
  67. @implementation Cup 
  68.  
  69. -(id) init { 
  70.  
  71. self = [super init]; 
  72.  
  73. if ( self ) { 
  74.  
  75. [self setLevel: 0]; 
  76.  
  77. } 
  78.  
  79. return self; 
  80.  
  81. } 
  82.  
  83. -(int) level { 
  84.  
  85. return level; 
  86.  
  87. } 
  88.  
  89. -(void) setLevel: (int) l { 
  90.  
  91. llevel = l; 
  92.  
  93. if ( level > 100 ) { 
  94.  
  95. // throw overflow 
  96.  
  97. NSException *e = [CupOverflowException 
  98.  
  99. exceptionWithName: @"CupOverflowException" 
  100.  
  101. reason: @"The level is above 100" 
  102.  
  103. userInfo: nil]; 
  104.  
  105. @throw e; 
  106.  
  107. } else if ( level >= 50 ) { 
  108.  
  109. // throw warning 
  110.  
  111. NSException *e = [CupWarningException 
  112.  
  113. exceptionWithName: @"CupWarningException" 
  114.  
  115. reason: @"The level is above or at 50" 
  116.  
  117. userInfo: nil]; 
  118.  
  119. @throw e; 
  120.  
  121. } else if ( level < 0 ) { 
  122.  
  123. // throw exception 
  124.  
  125. NSException *e = [NSException 
  126.  
  127. exceptionWithName: @"CupUnderflowException" 
  128.  
  129. reason: @"The level is below 0" 
  130.  
  131. userInfo: nil]; 
  132.  
  133. @throw e; 
  134.  
  135. } 
  136.  
  137. } 
  138.  
  139. -(void) fill { 
  140.  
  141. [self setLevel: level + 10]; 
  142.  
  143. } 
  144.  
  145. -(void) empty { 
  146.  
  147. [self setLevel: level - 10]; 
  148.  
  149. } 
  150.  
  151. -(void) print { 
  152.  
  153. printf( "Cup level is: %i ", level ); 
  154.  
  155. } 
  156.  
  157. @end 
  158.  
  159. main.m 
  160.  
  161. #import "Cup.h" 
  162.  
  163. #import "CupOverflowException.h" 
  164.  
  165. #import "CupWarningException.h" 
  166.  
  167. #import 
  168.  
  169. #import 
  170.  
  171. #import 
  172.  
  173. #import 
  174.  
  175. int main( int argc, const char *argv[] ) { 
  176.  
  177. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
  178.  
  179. Cup *cup = [[Cup alloc] init]; 
  180.  
  181. int i; 
  182.  
  183. // this will work 
  184.  
  185. for ( i = 0; i < 4; i++ ) { 
  186.  
  187. [cup fill]; 
  188.  
  189. [cup print]; 
  190.  
  191. } 
  192.  
  193. // this will throw exceptions 
  194.  
  195. for ( i = 0; i < 7; i++ ) { 
  196.  
  197. @try { 
  198.  
  199. [cup fill]; 
  200.  
  201. } @catch ( CupWarningException *e ) { 
  202.  
  203. printf( "%s: ", [[e name] cString] ); 
  204.  
  205. } @catch ( CupOverflowException *e ) { 
  206.  
  207. printf( "%s: ", [[e name] cString] ); 
  208.  
  209. } @finally { 
  210.  
  211. [cup print]; 
  212.  
  213. } 
  214.  
  215. } 
  216.  
  217. // throw a generic exception 
  218.  
  219. @try { 
  220.  
  221. [cup setLevel: -1]; 
  222.  
  223. } @catch ( NSException *e ) { 
  224.  
  225. printf( "%s: %s ", [[e name] cString], [[e reason] cString] ); 
  226.  
  227. } 
  228.  
  229. // free memory 
  230.  
  231. [cup release]; 
  232.  
  233. [pool release]; 
  234.  
  235. } 

  output

  1. Cup level is: 10 
  2.  
  3. Cup level is: 20 
  4.  
  5. Cup level is: 30 
  6.  
  7. Cup level is: 40 
  8.  
  9. CupWarningException: Cup level is: 50 
  10.  
  11. CupWarningException: Cup level is: 60 
  12.  
  13. CupWarningException: Cup level is: 70 
  14.  
  15. CupWarningException: Cup level is: 80 
  16.  
  17. CupWarningException: Cup level is: 90 
  18.  
  19. CupWarningException: Cup level is: 100 
  20.  
  21. CupOverflowException: Cup level is: 110 
  22.  
  23. CupUnderflowException: The level is below 0 

  NSAutoreleasePool 是一个记忆体管理类别。现在先别管它是干嘛的。

  Exceptions(异常情况)的丢出不需要扩充(extend)NSException 物件,你可简单的用 id 来代表它: @catch ( id e ) { ... }

  还有一个 finally 区块,它的行为就像 Java 的异常处理方式,finally 区块的内容保证会被唿叫。

  Cup.m 裡的 @"CupOverflowException" 是一个 NSString 常数物件。在 Objective-C 中,@ 符号通常用来代表这是语言的衍生部分。C 语言形式的字串(C string)就像 C/C++ 一样是 "String constant" 的形式,型别为 char *。 

   


  继承、多型(Inheritance, Polymorphism)以及其他物件导向功能

  id 型别

  Objective-C 有种叫做 id 的型别,它的运作有时候像是 void*,不过它却严格规定只能用在物件。Objective-C 与 Java 跟 C++ 不一样,你在唿叫一个物件的 method 时,并不需要知道这个物件的型别。当然这个 method 一定要存在,这称为 Objective-C 的讯息传递。

  1. Fraction.h 
  2.  
  3. #import 
  4.  
  5. @interface Fraction: NSObject { 
  6.  
  7. int numerator; 
  8.  
  9. int denominator; 
  10.  
  11. } 
  12.  
  13. -(Fraction*) initWithNumerator: (int) n denominator: (int) d; 
  14.  
  15. -(void) print; 
  16.  
  17. -(void) setNumerator: (int) d; 
  18.  
  19. -(void) setDenominator: (int) d; 
  20.  
  21. -(void) setNumerator: (int) n andDenominator: (int) d; 
  22.  
  23. -(int) numerator; 
  24.  
  25. -(int) denominator; 
  26.  
  27. @end 
  28.  
  29. Fraction.m 
  30.  
  31. #import "Fraction.h" 
  32.  
  33. #import 
  34.  
  35. @implementation Fraction 
  36.  
  37. -(Fraction*) initWithNumerator: (int) n denominator: (int) d { 
  38.  
  39. self = [super init]; 
  40.  
  41. if ( self ) { 
  42.  
  43. [self setNumerator: n andDenominator: d]; 
  44.  
  45. } 
  46.  
  47. return self; 
  48.  
  49. } 
  50.  
  51. -(void) print { 
  52.  
  53. printf( "%i / %i", numerator, denominator ); 
  54.  
  55. } 
  56.  
  57. -(void) setNumerator: (int) n { 
  58.  
  59. nnumerator = n; 
  60.  
  61. } 
  62.  
  63. -(void) setDenominator: (int) d { 
  64.  
  65. ddenominator = d; 
  66.  
  67. } 
  68.  
  69. -(void) setNumerator: (int) n andDenominator: (int) d { 
  70.  
  71. nnumerator = n; 
  72.  
  73. ddenominator = d; 
  74.  
  75. } 
  76.  
  77. -(int) denominator { 
  78.  
  79. return denominator; 
  80.  
  81. } 
  82.  
  83. -(int) numerator { 
  84.  
  85. return numerator; 
  86.  
  87. } 
  88.  
  89. @end 
  90.  
  91. Complex.h 
  92.  
  93. #import 
  94.  
  95. @interface Complex: NSObject { 
  96.  
  97. double real; 
  98.  
  99. double imaginary; 
  100.  
  101. } 
  102.  
  103. -(Complex*) initWithReal: (double) r andImaginary: (double) i; 
  104.  
  105. -(void) setReal: (double) r; 
  106.  
  107. -(void) seTIMaginary: (double) i; 
  108.  
  109. -(void) setReal: (double) r andImaginary: (double) i; 
  110.  
  111. -(double) real; 
  112.  
  113. -(double) imaginary; 
  114.  
  115. -(void) print; 
  116.  
  117. @end 
  118.  
  119. Complex.m 
  120.  
  121. #import "Complex.h" 
  122.  
  123. #import 
  124.  
  125. @implementation Complex 
  126.  
  127. -(Complex*) initWithReal: (double) r andImaginary: (double) i { 
  128.  
  129. self = [super init]; 
  130.  
  131. if ( self ) { 
  132.  
  133. [self setReal: r andImaginary: i]; 
  134.  
  135. } 
  136.  
  137. return self; 
  138.  
  139. } 
  140.  
  141. -(void) setReal: (double) r { 
  142.  
  143. rreal = r; 
  144.  
  145. } 
  146.  
  147. -(void) setImaginary: (double) i { 
  148.  
  149. iimaginary = i; 
  150.  
  151. } 
  152.  
  153. -(void) setReal: (double) r andImaginary: (double) i { 
  154.  
  155. rreal = r; 
  156.  
  157. iimaginary = i; 
  158.  
  159. } 
  160.  
  161. -(double) real { 
  162.  
  163. return real; 
  164.  
  165. } 
  166.  
  167. -(double) imaginary { 
  168.  
  169. return imaginary; 
  170.  
  171. } 
  172.  
  173. -(void) print { 
  174.  
  175. printf( "%_f + %_fi", real, imaginary ); 
  176.  
  177. } 
  178.  
  179. @end 
  180.  
  181. main.m 
  182.  
  183. #import 
  184.  
  185. #import "Fraction.h" 
  186.  
  187. #import "Complex.h" 
  188.  
  189. int main( int argc, const char *argv[] ) { 
  190.  
  191. // create a new instance 
  192.  
  193. Fraction *frac = [[Fraction alloc] initWithNumerator: 1 denominator: 10]; 
  194.  
  195. Complex *comp = [[Complex alloc] initWithReal: 10 andImaginary: 15]; 
  196.  
  197. id number; 
  198.  
  199. // print fraction 
  200.  
  201. number = frac; 
  202.  
  203. printf( "The fraction is: " ); 
  204.  
  205. [number print]; 
  206.  
  207. printf( " " ); 
  208.  
  209. // print complex 
  210.  
  211. number = comp; 
  212.  
  213. printf( "The complex number is: " ); 
  214.  
  215. [number print]; 
  216.  
  217. printf( " " ); 
  218.  
  219. // free memory 
  220.  
  221. [frac release]; 
  222.  
  223. [comp release]; 
  224.  
  225. return 0; 
  226.  
  227. } 

  output

  1. The fraction is: 1 / 10 
  2.  
  3. The complex number is: 10.000000 + 15.000000i 

  这种动态连结有显而易见的好处。你不需要知道你唿叫 method 的那个东西是什么型别,如果这个物件对这个讯息有反应,那就会唤起这个 method。这也不会牵涉到一堆繁琐的转型动作,比如在 Java 裡唿叫一个整数物件的 .intValue() 就得先转型,然后才能唿叫这个 method。


  继承(Inheritance)

  1. Rectangle.h 
  2.  
  3. #import 
  4.  
  5. @interface Rectangle: NSObject { 
  6.  
  7. int width; 
  8.  
  9. int height; 
  10.  
  11. } 
  12.  
  13. -(Rectangle*) initWithWidth: (int) w height: (int) h; 
  14.  
  15. -(void) setWidth: (int) w; 
  16.  
  17. -(void) setHeight: (int) h; 
  18.  
  19. -(void) setWidth: (int) w height: (int) h; 
  20.  
  21. -(int) width; 
  22.  
  23. -(int) height; 
  24.  
  25. -(void) print; 
  26.  
  27. @end 
  28.  
  29. Rectangle.m 
  30.  
  31. #import "Rectangle.h" 
  32.  
  33. #import 
  34.  
  35. @implementation Rectangle 
  36.  
  37. -(Rectangle*) initWithWidth: (int) w height: (int) h { 
  38.  
  39. self = [super init]; 
  40.  
  41. if ( self ) { 
  42.  
  43. [self setWidth: w height: h]; 
  44.  
  45. } 
  46.  
  47. return self; 
  48.  
  49. } 
  50.  
  51. -(void) setWidth: (int) w { 
  52.  
  53. wwidth = w; 
  54.  
  55. } 
  56.  
  57. -(void) setHeight: (int) h { 
  58.  
  59. hheight = h; 
  60.  
  61. } 
  62.  
  63. -(void) setWidth: (int) w height: (int) h { 
  64.  
  65. wwidth = w; 
  66.  
  67. hheight = h; 
  68.  
  69. } 
  70.  
  71. -(int) width { 
  72.  
  73. return width; 
  74.  
  75. } 
  76.  
  77. -(int) height { 
  78.  
  79. return height; 
  80.  
  81. } 
  82.  
  83. -(void) print { 
  84.  
  85. printf( "width = %i, height = %i", width, height ); 
  86.  
  87. } 
  88.  
  89. @end 
  90.  
  91. Square.h 
  92.  
  93. #import "Rectangle.h" 
  94.  
  95. @interface Square: Rectangle 
  96.  
  97. -(Square*) initWithSize: (int) s; 
  98.  
  99. -(void) setSize: (int) s; 
  100.  
  101. -(int) size; 
  102.  
  103. @end 
  104.  
  105. Square.m 
  106.  
  107. #import "Square.h" 
  108.  
  109. @implementation Square 
  110.  
  111. -(Square*) initWithSize: (int) s { 
  112.  
  113. self = [super init]; 
  114.  
  115. if ( self ) { 
  116.  
  117. [self setSize: s]; 
  118.  
  119. } 
  120.  
  121. return self; 
  122.  
  123. } 
  124.  
  125. -(void) setSize: (int) s { 
  126.  
  127. width = s; 
  128.  
  129. height = s; 
  130.  
  131. } 
  132.  
  133. -(int) size { 
  134.  
  135. return width; 
  136.  
  137. } 
  138.  
  139. -(void) setWidth: (int) w { 
  140.  
  141. [self setSize: w]; 
  142.  
  143. } 
  144.  
  145. -(void) setHeight: (int) h { 
  146.  
  147. [self setSize: h]; 
  148.  
  149. } 
  150.  
  151. @end 
  152.  
  153. main.m 
  154.  
  155. #import "Square.h" 
  156.  
  157. #import "Rectangle.h" 
  158.  
  159. #import 
  160.  
  161. int main( int argc, const char *argv[] ) { 
  162.  
  163. Rectangle *rec = [[Rectangle alloc] initWithWidth: 10 height: 20]; 
  164.  
  165. Square *sq = [[Square alloc] initWithSize: 15]; 
  166.  
  167. // print em 
  168.  
  169. printf( "Rectangle: " ); 
  170.  
  171. [rec print]; 
  172.  
  173. printf( " " ); 
  174.  
  175. printf( "Square: " ); 
  176.  
  177. [sq print]; 
  178.  
  179. printf( " " ); 
  180.  
  181. // update square 
  182.  
  183. [sq setWidth: 20]; 
  184.  
  185. printf( "Square after change: " ); 
  186.  
  187. [sq print]; 
  188.  
  189. printf( " " ); 
  190.  
  191. // free memory 
  192.  
  193. [rec release]; 
  194.  
  195. [sq release]; 
  196.  
  197. return 0; 
  198.  
  199. } 

  output

  1. Rectangle: width = 10, height = 20 
  2.  
  3. Square: width = 15, height = 15 
  4.  
  5. Square after change: width = 20, height = 20 

  继承在 Objective-C 裡比较像 Java。当你扩充你的 super class(所以只能有一个 parent),你想自订这个 super class 的 method,只要简单的在你的 child class implementation 裡放上新的实作内容即可。而不需要 C++ 裡呆呆的 virtual table。

  这裡还有一个值得玩味的地方,如果你企图像这样去唿叫 rectangle 的 constructor: Square *sq = [[Square alloc] initWithWidth: 10 height: 15],会发生什么事?答案是会产生一个编译器错误。因为 rectangle constructor 回传的型别是 Rectangle*,而不是 Square*,所以这行不通。在某种情况下如果你真想这样用,使用 id 型别会是很好的选择。如果你想使用 parent 的 constructor,只要把 Rectangle* 回传型别改成 id 即可。


  动态识别(Dynamic types)

  这裡有一些用于 Objective-C 动态识别的 methods(说明部分採中英并列,因为我觉得英文比较传神,中文怎么译都怪):

  1. -(BOOL) isKindOfClass: classObjis object a descendent or member of classObj 

  此物件是否是 classObj 的子孙或一员

  1. -(BOOL) isMemberOfClass: classObjis object a member of classObj 

  此物件是否是 classObj 的一员

  1. -(BOOL) respondsToSelector: selectordoes the object have a method named specifiec by the selector 

  此物件是否有叫做 selector 的 method

  1. +(BOOL) instancesRespondToSelector: selectordoes an object created by this class have the ability to respond to the specified selector 

  此物件是否是由有能力回应指定 selector 的物件所产生

  1. -(id) performSelector: selectorinvoke the specified selector on the object 

  唤起此物件的指定 selector

  所有继承自 NSObject 都有一个可回传一个 class 物件的 class method。这非常近似于 Java 的 getClass() method。这个 class 物件被使用于前述的 methods 中。

  Selectors 在 Objective-C 用以表示讯息。下一个範例会秀出建立 selector 的语法。

  1. main.m 
  2.  
  3. #import "Square.h" 
  4.  
  5. #import "Rectangle.h" 
  6.  
  7. #import 
  8.  
  9. int main( int argc, const char *argv[] ) { 
  10.  
  11. Rectangle *rec = [[Rectangle alloc] initWithWidth: 10 height: 20]; 
  12.  
  13. Square *sq = [[Square alloc] initWithSize: 15]; 
  14.  
  15. // isMemberOfClass 
  16.  
  17. // true 
  18.  
  19. if ( [sq isMemberOfClass: [Square class]] == YES ) { 
  20.  
  21. printf( "square is a member of square class " ); 
  22.  
  23. } 
  24.  
  25. // false 
  26.  
  27. if ( [sq isMemberOfClass: [Rectangle class]] == YES ) { 
  28.  
  29. printf( "square is a member of rectangle class " ); 
  30.  
  31. } 
  32.  
  33. // false 
  34.  
  35. if ( [sq isMemberOfClass: [NSObject class]] == YES ) { 
  36.  
  37. printf( "square is a member of object class " ); 
  38.  
  39. } 
  40.  
  41. // isKindOfClass 
  42.  
  43. // true 
  44.  
  45. if ( [sq isKindOfClass: [Square class]] == YES ) { 
  46.  
  47. printf( "square is a kind of square class " ); 
  48.  
  49. } 
  50.  
  51. // true 
  52.  
  53. if ( [sq isKindOfClass: [Rectangle class]] == YES ) { 
  54.  
  55. printf( "square is a kind of rectangle class " ); 
  56.  
  57. } 
  58.  
  59. // true 
  60.  
  61. if ( [sq isKindOfClass: [NSObject class]] == YES ) { 
  62.  
  63. printf( "square is a kind of object class " ); 
  64.  
  65. } 
  66.  
  67. // respondsToSelector 
  68.  
  69. // true 
  70.  
  71. if ( [sq respondsToSelector: @selector( setSize: )] == YES ) { 
  72.  
  73. printf( "square responds to setSize: method " ); 
  74.  
  75. } 
  76.  
  77. // false 
  78.  
  79. if ( [sq respondsToSelector: @selector( nonExistant )] == YES ) { 
  80.  
  81. printf( "square responds to nonExistant method " ); 
  82.  
  83. } 
  84.  
  85. // true 
  86.  
  87. if ( [Square respondsToSelector: @selector( alloc )] == YES ) { 
  88.  
  89. printf( "square class responds to alloc method " ); 
  90.  
  91. } 
  92.  
  93. // instancesRespondToSelector 
  94.  
  95. // false 
  96.  
  97. if ( [Rectangle instancesRespondToSelector: @selector( setSize: )] == YES ) { 
  98.  
  99. printf( "rectangle instance responds to setSize: method " ); 
  100.  
  101. } 
  102.  
  103. // true 
  104.  
  105. if ( [Square instancesRespondToSelector: @selector( setSize: )] == YES ) { 
  106.  
  107. printf( "square instance responds to setSize: method " ); 
  108.  
  109. } 
  110.  
  111. // free memory 
  112.  
  113. [rec release]; 
  114.  
  115. [sq release]; 
  116.  
  117. return 0; 
  118.  
  119. } 

  output

  1. square is a member of square class 
  2.  
  3. square is a kind of square class 
  4.  
  5. square is a kind of rectangle class 
  6.  
  7. square is a kind of object class 
  8.  
  9. square responds to setSize: method 
  10.  
  11. square class responds to alloc method 
  12.  
  13. square instance responds to setSize: method 
  14.  
  15. Categories 

  当你想要为某个 class 新增 methods,你通常会扩充(extend,即继承)它。然而这不一定是个完美解法,特别是你想要重写一个 class 的某个功能,但你却没有塬始码时。Categories 允许你在现有的 class 加入新功能,但不需要扩充它。Ruby 语言也有类似的功能。

  1. FractionMath.h 
  2.  
  3. #import "Fraction.h" 
  4.  
  5. @interface Fraction (Math) 
  6.  
  7. -(Fraction*) add: (Fraction*) f; 
  8.  
  9. -(Fraction*) mul: (Fraction*) f; 
  10.  
  11. -(Fraction*) div: (Fraction*) f; 
  12.  
  13. -(Fraction*) sub: (Fraction*) f; 
  14.  
  15. @end 
  16.  
  17. FractionMath.m 
  18.  
  19. #import "FractionMath.h" 
  20.  
  21. @implementation Fraction (Math) 
  22.  
  23. -(Fraction*) add: (Fraction*) f { 
  24.  
  25. return [[Fraction alloc] initWithNumerator: numerator * [f denominator] + 
  26.  
  27. denominator * [f numerator] 
  28.  
  29. denominator: denominator * [f denominator]]; 
  30.  
  31. } 
  32.  
  33. -(Fraction*) mul: (Fraction*) f { 
  34.  
  35. return [[Fraction alloc] initWithNumerator: numerator * [f numerator] 
  36.  
  37. denominator: denominator * [f denominator]]; 
  38.  
  39. } 
  40.  
  41. -(Fraction*) div: (Fraction*) f { 
  42.  
  43. return [[Fraction alloc] initWithNumerator: numerator * [f denominator] 
  44.  
  45. denominator: denominator * [f numerator]]; 
  46.  
  47. } 
  48.  
  49. -(Fraction*) sub: (Fraction*) f { 
  50.  
  51. return [[Fraction alloc] initWithNumerator: numerator * [f denominator] - 
  52.  
  53. denominator * [f numerator] 
  54.  
  55. denominator: denominator * [f denominator]]; 
  56.  
  57. } 
  58.  
  59. @end 
  60.  
  61. main.m 
  62.  
  63. #import 
  64.  
  65. #import "Fraction.h" 
  66.  
  67. #import "FractionMath.h" 
  68.  
  69. int main( int argc, const char *argv[] ) { 
  70.  
  71. // create a new instance 
  72.  
  73. Fraction *frac1 = [[Fraction alloc] initWithNumerator: 1 denominator: 3]; 
  74.  
  75. Fraction *frac2 = [[Fraction alloc] initWithNumerator: 2 denominator: 5]; 
  76.  
  77. Fraction *frac3 = [frac1 mul: frac2]; 
  78.  
  79. // print it 
  80.  
  81. [frac1 print]; 
  82.  
  83. printf( " * " ); 
  84.  
  85. [frac2 print]; 
  86.  
  87. printf( " = " ); 
  88.  
  89. [frac3 print]; 
  90.  
  91. printf( " " ); 
  92.  
  93. // free memory 
  94.  
  95. [frac1 release]; 
  96.  
  97. [frac2 release]; 
  98.  
  99. [frac3 release]; 
  100.  
  101. return 0; 
  102.  
  103. } 

  output

  1. 1/3 * 2/5 = 2/15 

  重点是 @implementation 跟 @interface 这两行:@interface Fraction (Math) 以及 @implementation Fraction (Math).

  (同一个 class)只能有一个同名的 category,其他的 categories 得加上不同的、独一无二的名字。

  Categories 在建立 private methods 时十分有用。因为 Objective-C 并没有像 Java 这种 private/protected/public methods 的概念,所以必须要使用 categories 来达成这种功能。作法是把 private method 从你的 class header (.h) 档案移到 implementation (.m) 档案。以下是此种作法一个简短的範例。

  1. MyClass.h 
  2.  
  3. #import 
  4.  
  5. @interface MyClass: NSObject 
  6.  
  7. -(void) publicMethod; 
  8.  
  9. @end 
  10.  
  11. MyClass.m 
  12.  
  13. #import "MyClass.h" 
  14.  
  15. #import 
  16.  
  17. @implementation MyClass 
  18.  
  19. -(void) publicMethod { 
  20.  
  21. printf( "public method " ); 
  22.  
  23. } 
  24.  
  25. @end 
  26.  
  27. // private methods 
  28.  
  29. @interface MyClass (Private) 
  30.  
  31. -(void) privateMethod; 
  32.  
  33. @end 
  34.  
  35. @implementation MyClass (Private) 
  36.  
  37. -(void) privateMethod { 
  38.  
  39. printf( "private method " ); 
  40.  
  41. } 
  42.  
  43. @end 
  44.  
  45. main.m 
  46.  
  47. #import "MyClass.h" 
  48.  
  49. int main( int argc, const char *argv[] ) { 
  50.  
  51. MyClass *obj = [[MyClass alloc] init]; 
  52.  
  53. // this compiles 
  54.  
  55. [obj publicMethod]; 
  56.  
  57. // this throws errors when compiling 
  58.  
  59. //[obj privateMethod]; 
  60.  
  61. // free memory 
  62.  
  63. [obj release]; 
  64.  
  65. return 0; 
  66.  
  67. } 

  output

  1. public method 
  2.  
  3. Posing 

  Posing 有点像 categories,但是不太一样。它允许你扩充一个 class,并且全面性地的扮演(pose)这个 super class。例如:你有一个扩充 NSArray 的 NSArrayChild 物件。如果你让 NSArrayChild 扮演 NSArray,则在你的程式码中所有的 NSArray 都会自动被替代为 NSArrayChild。

  1. FractionB.h 
  2.  
  3. #import "Fraction.h" 
  4.  
  5. @interface FractionB: Fraction 
  6.  
  7. -(void) print; 
  8.  
  9. @end 
  10.  
  11. FractionB.m 
  12.  
  13. #import "FractionB.h" 
  14.  
  15. #import 
  16.  
  17. @implementation FractionB 
  18.  
  19. -(void) print { 
  20.  
  21. printf( "(%i/%i)", numerator, denominator ); 
  22.  
  23. } 
  24.  
  25. @end 
  26.  
  27. main.m 
  28.  
  29. #import 
  30.  
  31. #import "Fraction.h" 
  32.  
  33. #import "FractionB.h" 
  34.  
  35. int main( int argc, const char *argv[] ) { 
  36.  
  37. Fraction *frac = [[Fraction alloc] initWithNumerator: 3 denominator: 10]; 
  38.  
  39. // print it 
  40.  
  41. printf( "The fraction is: " ); 
  42.  
  43. [frac print]; 
  44.  
  45. printf( " " ); 
  46.  
  47. // make FractionB pose as Fraction 
  48.  
  49. [FractionB poSeasClass: [Fraction class]]; 
  50.  
  51. Fraction *frac2 = [[Fraction alloc] initWithNumerator: 3 denominator: 10]; 
  52.  
  53. // print it 
  54.  
  55. printf( "The fraction is: " ); 
  56.  
  57. [frac2 print]; 
  58.  
  59. printf( " " ); 
  60.  
  61. // free memory 
  62.  
  63. [frac release]; 
  64.  
  65. [frac2 release]; 
  66.  
  67. return 0; 
  68.  
  69. } 

  output

  1. The fraction is: 3/10 
  2.  
  3. The fraction is: (3/10) 

  这个程式的输出中,第一个 fraction 会输出 3/10,而第二个会输出 (3/10)。这是 FractionB 中实作的方式。

  poseAsClass 这个 method 是 NSObject 的一部份,它允许 subclass 扮演 superclass。


  Protocols

  Objective-C 裡的 Protocol 与 Java 的 interface 或是 C++ 的 purely virtual class 相同。

  1. Printing.h 
  2.  
  3. @protocol Printing 
  4.  
  5. -(void) print; 
  6.  
  7. @end 
  8.  
  9. Fraction.h 
  10.  
  11. #import 
  12.  
  13. #import "Printing.h" 
  14.  
  15. @interface Fraction: NSObject { 
  16.  
  17. int numerator; 
  18.  
  19. int denominator; 
  20.  
  21. } 
  22.  
  23. -(Fraction*) initWithNumerator: (int) n denominator: (int) d; 
  24.  
  25. -(void) setNumerator: (int) d; 
  26.  
  27. -(void) setDenominator: (int) d; 
  28.  
  29. -(void) setNumerator: (int) n andDenominator: (int) d; 
  30.  
  31. -(int) numerator; 
  32.  
  33. -(int) denominator; 
  34.  
  35. @end 
  36.  
  37. Fraction.m 
  38.  
  39. #import "Fraction.h" 
  40.  
  41. #import 
  42.  
  43. @implementation Fraction 
  44.  
  45. -(Fraction*) initWithNumerator: (int) n denominator: (int) d { 
  46.  
  47. self = [super init]; 
  48.  
  49. if ( self ) { 
  50.  
  51. [self setNumerator: n andDenominator: d]; 
  52.  
  53. } 
  54.  
  55. return self; 
  56.  
  57. } 
  58.  
  59. -(void) print { 
  60.  
  61. printf( "%i/%i", numerator, denominator ); 
  62.  
  63. } 
  64.  
  65. -(void) setNumerator: (int) n { 
  66.  
  67. nnumerator = n; 
  68.  
  69. } 
  70.  
  71. -(void) setDenominator: (int) d { 
  72.  
  73. ddenominator = d; 
  74.  
  75. } 
  76.  
  77. -(void) setNumerator: (int) n andDenominator: (int) d { 
  78.  
  79. nnumerator = n; 
  80.  
  81. ddenominator = d; 
  82.  
  83. } 
  84.  
  85. -(int) denominator { 
  86.  
  87. return denominator; 
  88.  
  89. } 
  90.  
  91. -(int) numerator { 
  92.  
  93. return numerator; 
  94.  
  95. } 
  96.  
  97. -(Fraction*) copyWithZone: (NSZone*) zone { 
  98.  
  99. return [[Fraction allocWithZone: zone] initWithNumerator: numerator 
  100.  
  101. denominator: denominator]; 
  102.  
  103. } 
  104.  
  105. @end 
  106.  
  107. Complex.h 
  108.  
  109. #import 
  110.  
  111. #import "Printing.h" 
  112.  
  113. @interface Complex: NSObject { 
  114.  
  115. double real; 
  116.  
  117. double imaginary; 
  118.  
  119. } 
  120.  
  121. -(Complex*) initWithReal: (double) r andImaginary: (double) i; 
  122.  
  123. -(void) setReal: (double) r; 
  124.  
  125. -(void) setImaginary: (double) i; 
  126.  
  127. -(void) setReal: (double) r andImaginary: (double) i; 
  128.  
  129. -(double) real; 
  130.  
  131. -(double) imaginary; 
  132.  
  133. @end 
  134.  
  135. Complex.m 
  136.  
  137. #import "Complex.h" 
  138.  
  139. #import 
  140.  
  141. @implementation Complex 
  142.  
  143. -(Complex*) initWithReal: (double) r andImaginary: (double) i { 
  144.  
  145. self = [super init]; 
  146.  
  147. if ( self ) { 
  148.  
  149. [self setReal: r andImaginary: i]; 
  150.  
  151. } 
  152.  
  153. return self; 
  154.  
  155. } 
  156.  
  157. -(void) setReal: (double) r { 
  158.  
  159. rreal = r; 
  160.  
  161. } 
  162.  
  163. -(void) setImaginary: (double) i { 
  164.  
  165. iimaginary = i; 
  166.  
  167. } 
  168.  
  169. -(void) setReal: (double) r andImaginary: (double) i { 
  170.  
  171. rreal = r; 
  172.  
  173. iimaginary = i; 
  174.  
  175. } 
  176.  
  177. -(double) real { 
  178.  
  179. return real; 
  180.  
  181. } 
  182.  
  183. -(double) imaginary { 
  184.  
  185. return imaginary; 
  186.  
  187. } 
  188.  
  189. -(void) print { 
  190.  
  191. printf( "%_f + %_fi", real, imaginary ); 
  192.  
  193. } 
  194.  
  195. @end 
  196.  
  197. main.m 
  198.  
  199. #import 
  200.  
  201. #import "Fraction.h" 
  202.  
  203. #import "Complex.h" 
  204.  
  205. int main( int argc, const char *argv[] ) { 
  206.  
  207. // create a new instance 
  208.  
  209. Fraction *frac = [[Fraction alloc] initWithNumerator: 3 denominator: 10]; 
  210.  
  211. Complex *comp = [[Complex alloc] initWithReal: 5 andImaginary: 15]; 
  212.  
  213. id printable; 
  214.  
  215. id copyPrintable; 
  216.  
  217. // print it 
  218.  
  219. printable = frac; 
  220.  
  221. printf( "The fraction is: " ); 
  222.  
  223. [printable print]; 
  224.  
  225. printf( " " ); 
  226.  
  227. // print complex 
  228.  
  229. printable = comp; 
  230.  
  231. printf( "The complex number is: " ); 
  232.  
  233. [printable print]; 
  234.  
  235. printf( " " ); 
  236.  
  237. // this compiles because Fraction comforms to both Printing and NSCopyable 
  238.  
  239. copyPrintable = frac; 
  240.  
  241. // this doesn't compile because Complex only conforms to Printing 
  242.  
  243. //copyPrintable = comp; 
  244.  
  245. // test conformance 
  246.  
  247. // true 
  248.  
  249. if ( [frac conformsToProtocol: @protocol( NSCopying )] == YES ) { 
  250.  
  251. printf( "Fraction conforms to NSCopying " ); 
  252.  
  253. } 
  254.  
  255. // false 
  256.  
  257. if ( [comp conformsToProtocol: @protocol( NSCopying )] == YES ) { 
  258.  
  259. printf( "Complex conforms to NSCopying " ); 
  260.  
  261. } 
  262.  
  263. // free memory 
  264.  
  265. [frac release]; 
  266.  
  267. [comp release]; 
  268.  
  269. return 0; 
  270.  
  271. } 

  output

  1. The fraction is: 3/10 
  2.  
  3. The complex number is: 5.000000 + 15.000000i 
  4.  
  5. Fraction conforms to NSCopying 

  protocol 的宣告十分简单,基本上就是 @protocol ProtocolName (methods you must implement) @end。

  要遵从(conform)某个 protocol,将要遵从的 protocols 放在 <> 裡面,并以逗点分隔。如:@interface SomeClass

  protocol 要求实作的 methods 不需要放在 header 档裡面的 methods 列表中。如你所见,Complex.h 档案裡没有 -(void) print 的宣告,却还是要实作它,因为它(Complex class)遵从了这个 protocol。

  Objective-C 的介面系统有一个独一无二的观念是如何指定一个型别。比起 C++ 或 Java 的指定方式,如:Printing *someVar = ( Printing * ) frac; 你可以使用 id 型别加上 protocol:id var = frac;。这让你可以动态地指定一个要求多个 protocol 的型别,却从头到尾只用了一个变数。如: var = frac;

  就像使用@selector 来测试物件的继承关係,你可以使用 @protocol 来测试物件是否遵从介面。如果物件遵从这个介面,[object conformsToProtocol: @protocol( SomeProtocol )] 会回传一个 YES 型态的 BOOL 物件。同样地,对 class 而言也能如法炮製 [SomeClass conformsToProtocol: @protocol( SomeProtocol )]。

  


  记忆体管理

  到目前为止我都刻意避开 Objective-C 的记忆体管理议题。你可以唿叫物件上的 dealloc,但是若物件裡包含其他物件的指标的话,要怎么办呢?要释放那些物件所佔据的记忆体也是一个必须关注的问题。当你使用 Foundation framework 建立 classes 时,它如何管理记忆体?这些稍后我们都会解释。

  注意:之前所有的範例都有正确的记忆体管理,以免你混淆。

  Retain and Release(保留与释放)

  Retain 以及 release 是两个继承自 NSObject 的物件都会有的 methods。每个物件都有一个内部计数器,可以用来追踪物件的 reference 个数。如果物件有 3 个 reference 时,不需要 dealloc 自己。但是如果计数器值到达 0 时,物件就得 dealloc 自己。[object retain] 会将计数器值加 1(值从 1 开始),[object release] 则将计数器值减 1。如果唿叫 [object release] 导致计数器到达 0,就会自动 dealloc。

  1. Fraction.m 
  2.  
  3. ... 
  4.  
  5. -(void) dealloc { 
  6.  
  7. printf( "Deallocing fraction " ); 
  8.  
  9. [super dealloc]; 
  10.  
  11. } 
  12.  
  13. ... 
  1. main.m 
  2.  
  3. #import "Fraction.h" 
  4.  
  5. #import 
  6.  
  7. int main( int argc, const char *argv[] ) { 
  8.  
  9. Fraction *frac1 = [[Fraction alloc] init]; 
  10.  
  11. Fraction *frac2 = [[Fraction alloc] init]; 
  12.  
  13. // print current counts 
  14.  
  15. printf( "Fraction 1 retain count: %i ", [frac1 retainCount] ); 
  16.  
  17. printf( "Fraction 2 retain count: %i ", [frac2 retainCount] ); 
  18.  
  19. // increment them 
  20.  
  21. [frac1 retain]; // 2 
  22.  
  23. [frac1 retain]; // 3 
  24.  
  25. [frac2 retain]; // 2 
  26.  
  27. // print current counts 
  28.  
  29. printf( "Fraction 1 retain count: %i ", [frac1 retainCount] ); 
  30.  
  31. printf( "Fraction 2 retain count: %i ", [frac2 retainCount] ); 
  32.  
  33. // decrement 
  34.  
  35. [frac1 release]; // 2 
  36.  
  37. [frac2 release]; // 1 
  38.  
  39. // print current counts 
  40.  
  41. printf( "Fraction 1 retain count: %i ", [frac1 retainCount] ); 
  42.  
  43. printf( "Fraction 2 retain count: %i ", [frac2 retainCount] ); 
  44.  
  45. // release them until they dealloc themselves 
  46.  
  47. [frac1 release]; // 1 
  48.  
  49. [frac1 release]; // 0 
  50.  
  51. [frac2 release]; // 0 
  52.  
  53. } 

  output

  1. Fraction 1 retain count: 1 
  2.  
  3. Fraction 2 retain count: 1 
  4.  
  5. Fraction 1 retain count: 3 
  6.  
  7. Fraction 2 retain count: 2 
  8.  
  9. Fraction 1 retain count: 2 
  10.  
  11. Fraction 2 retain count: 1 
  12.  
  13. Deallocing fraction 
  14.  
  15. Deallocing fraction 

  Retain call 增加计数器值,而 release call 减少它。你可以唿叫 [obj retainCount] 来取得计数器的 int 值。 当当 retainCount 到达 0,两个物件都会 dealloc 自己,所以可以看到印出了两个 "Deallocing fraction"。

  Dealloc

  当你的物件包含其他物件时,就得在 dealloc 自己时释放它们。Objective-C 的一个优点是你可以传递讯息给 nil,所以不需要经过一堆防错测试来释放一个物件。

  AddressCard.h

  1. #import 
  2.  
  3. #import 
  4.  
  5. @interface AddressCard: NSObject { 
  6.  
  7. NSString *first; 
  8.  
  9. NSString *last; 
  10.  
  11. NSString *Email; 
  12.  
  13. } 
  14.  
  15. -(AddressCard*) initWithFirst: (NSString*) f 
  16.  
  17. last: (NSString*) l 
  18.  
  19. email: (NSString*) e; 
  20.  
  21. -(NSString*) first; 
  22.  
  23. -(NSString*) last; 
  24.  
  25. -(NSString*) email; 
  26.  
  27. -(void) setFirst: (NSString*) f; 
  28.  
  29. -(void) setLast: (NSString*) l; 
  30.  
  31. -(void) setEmail: (NSString*) e; 
  32.  
  33. -(void) setFirst: (NSString*) f 
  34.  
  35. last: (NSString*) l 
  36.  
  37. email: (NSString*) e; 
  38.  
  39. -(void) setFirst: (NSString*) f last: (NSString*) l; 
  40.  
  41. -(void) print; 
  42.  
  43. @end 
  44.  
  45. AddressCard.m 
  46.  
  47. #import "AddressCard.h" 
  48.  
  49. #import 
  50.  
  51. @implementation AddressCard 
  52.  
  53. -(AddressCard*) initWithFirst: (NSString*) f 
  54.  
  55. last: (NSString*) l 
  56.  
  57. email: (NSString*) e { 
  58.  
  59. self = [super init]; 
  60.  
  61. if ( self ) { 
  62.  
  63. [self setFirst: f last: l email: e]; 
  64.  
  65. } 
  66.  
  67. return self; 
  68.  
  69. } 
  70.  
  71. -(NSString*) first { 
  72.  
  73. return first; 
  74.  
  75. } 
  76.  
  77. -(NSString*) last { 
  78.  
  79. return last; 
  80.  
  81. } 
  82.  
  83. -(NSString*) email { 
  84.  
  85. return email; 
  86.  
  87. } 
  88.  
  89. -(void) setFirst: (NSString*) f { 
  90.  
  91. [f retain]; 
  92.  
  93. [first release]; 
  94.  
  95. ffirst = f; 
  96.  
  97. } 
  98.  
  99. -(void) setLast: (NSString*) l { 
  100.  
  101. [l retain]; 
  102.  
  103. [last release]; 
  104.  
  105. llast = l; 
  106.  
  107. } 
  108.  
  109. -(void) setEmail: (NSString*) e { 
  110.  
  111. [e retain]; 
  112.  
  113. [email release]; 
  114.  
  115. eemail = e; 
  116.  
  117. } 
  118.  
  119. -(void) setFirst: (NSString*) f 
  120.  
  121. last: (NSString*) l 
  122.  
  123. email: (NSString*) e { 
  124.  
  125. [self setFirst: f]; 
  126.  
  127. [self setLast: l]; 
  128.  
  129. [self setEmail: e]; 
  130.  
  131. } 
  132.  
  133. -(void) setFirst: (NSString*) f last: (NSString*) l { 
  134.  
  135. [self setFirst: f]; 
  136.  
  137. [self setLast: l]; 
  138.  
  139. } 
  140.  
  141. -(void) print { 
  142.  
  143. printf( "%s %s <%S> 
  144.  
  145. ", [first cString], 
  146.  
  147. [last cString], 
  148.  
  149. [email cString] ); 
  150.  
  151. } 
  152.  
  153. -(void) dealloc { 
  154.  
  155. [first release]; 
  156.  
  157. [last release]; 
  158.  
  159. [email release]; 
  160.  
  161. [super dealloc]; 
  162.  
  163. } 
  164.  
  165. @end 
  166.  
  167. main.m 
  168.  
  169. #import "AddressCard.h" 
  170.  
  171. #import 
  172.  
  173. #import 
  174.  
  175. int main( int argc, const char *argv[] ) { 
  176.  
  177. NSString *first =[[NSString alloc] initWithCString: "Tom"]; 
  178.  
  179. NSString *last = [[NSString alloc] initWithCString: "Jones"]; 
  180.  
  181. NSString *email = [[NSString alloc] initWithCString: "tom@"]; 
  182.  
  183. AddressCard *tom = [[AddressCard alloc] initWithFirst: first 
  184.  
  185. last: last 
  186.  
  187. email: email]; 
  188.  
  189. // we're done with the strings, so we must dealloc them 
  190.  
  191. [first release]; 
  192.  
  193. [last release]; 
  194.  
  195. [email release]; 
  196.  
  197. // print to show the retain count 
  198.  
  199. printf( "Retain count: %i ", [[tom first] retainCount] ); 
  200.  
  201. [tom print]; 
  202.  
  203. printf( " " ); 
  204.  
  205. // free memory 
  206.  
  207. [tom release]; 
  208.  
  209. return 0; 
  210.  
  211. } 

  output

  1. Retain count: 1 
  2.  
  3. Tom Jones  

  如 AddressCard.m,这个範例不仅展示如何撰写一个 dealloc method,也展示了如何 dealloc 成员变数。

  每个 set method 裡的叁个动作的顺序非常重要。假设你把自己当参数传给一个自己的 method(有点怪,不过确实可能发生)。若你先 release,「然后」才 retain,你会把自己给解构(destruct,相对于建构)!这就是为什么应该要 1) retain 2) release 3) 设值 的塬因。

  通常我们不会用 C 形式字串来初始化一个变数,因为它不支援 unicode。下一个 NSAutoreleasePool 的例子会用展示正确使用并初始化字串的方式。

  这只是处理成员变数记忆体管理的一种方式,另一种方式是在你的 set methods 裡面建立一份拷贝。

  Autorelease Pool

  当你想用 NSString 或其他 Foundation framework classes 来做更多程式设计工作时,你需要一个更有弹性的系统,也就是使用 Autorelease pools。

  当开发 Mac Cocoa 应用程式时,autorelease pool 会自动地帮你设定好。

  1. main.m 
  2.  
  3. #import 
  4.  
  5. #import 
  6.  
  7. #import 
  8.  
  9. int main( int argc, const char *argv[] ) { 
  10.  
  11. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
  12.  
  13. NSString *str1 = @"constant string"; 
  14.  
  15. NSString *str2 = [NSString stringWithString: @"string managed by the pool"]; 
  16.  
  17. NSString *str3 = [[NSString alloc] initWithString: @"self managed string"]; 
  18.  
  19. // print the strings 
  20.  
  21. printf( "%s retain count: %x ", [str1 cString], [str1 retainCount] ); 
  22.  
  23. printf( "%s retain count: %x ", [str2 cString], [str2 retainCount] ); 
  24.  
  25. printf( "%s retain count: %x ", [str3 cString], [str3 retainCount] ); 
  26.  
  27. // free memory 
  28.  
  29. [str3 release]; 
  30.  
  31. // free pool 
  32.  
  33. [pool release]; 
  34.  
  35. return 0; 
  36.  
  37. } 

  output

  1. constant string retain count: ffffffff 
  2.  
  3. string managed by the pool retain count: 1 
  4.  
  5. self managed string retain count: 1 

  如果你执行这个程式,你会发现几件事:第一件事,str1 的 retainCount 为 ffffffff。

  另一件事,虽然我只有 release str3,整个程式却还是处于完美的记忆体管理下,塬因是第一个常数字串已经自动被加到 autorelease pool 裡了。还有一件事,字串是由 stringWithString 产生的。这个 method 会产生一个 NSString class 型别的字串,并自动加进 autorelease pool。

  千万记得,要有良好的记忆体管理,像 [NSString stringWithString: @"String"] 这种 method 使用了 autorelease pool,而 alloc method 如 [[NSString alloc] initWithString: @"String"] 则没有使用 auto release pool。

  在 Objective-C 有两种管理记忆体的方法, 1) retain and release or 2) retain and release/autorelease。

  对于每个 retain,一定要对应一个 release 「或」一个 autorelease。

  下一个範例会展示我说的这点。

  1. Fraction.h 
  2.  
  3. ... 
  4.  
  5. +(Fraction*) fractionWithNumerator: (int) n denominator: (int) d; 
  6.  
  7. ... 
  8.  
  9. Fraction.m 
  10.  
  11. ... 
  12.  
  13. +(Fraction*) fractionWithNumerator: (int) n denominator: (int) d { 
  14.  
  15. Fraction *ret = [[Fraction alloc] initWithNumerator: n denominator: d]; 
  16.  
  17. [ret autorelease]; 
  18.  
  19. return ret; 
  20.  
  21. } 
  22.  
  23. ... 
  24.  
  25. main.m 
  26.  
  27. #import 
  28.  
  29. #import "Fraction.h" 
  30.  
  31. #import 
  32.  
  33. int main( int argc, const char *argv[] ) { 
  34.  
  35. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
  36.  
  37. Fraction *frac1 = [Fraction fractionWithNumerator: 2 denominator: 5]; 
  38.  
  39. Fraction *frac2 = [Fraction fractionWithNumerator: 1 denominator: 3]; 
  40.  
  41. // print frac 1 
  42.  
  43. printf( "Fraction 1: " ); 
  44.  
  45. [frac1 print]; 
  46.  
  47. printf( " " ); 
  48.  
  49. // print frac 2 
  50.  
  51. printf( "Fraction 2: " ); 
  52.  
  53. [frac2 print]; 
  54.  
  55. printf( " " ); 
  56.  
  57. // this causes a segmentation fault 
  58.  
  59. //[frac1 release]; 
  60.  
  61. // release the pool and all objects in it 
  62.  
  63. [pool release]; 
  64.  
  65. return 0; 
  66.  
  67. } 

  output

  1. Fraction 1: 2/5 
  2.  
  3. Fraction 2: 1/3 

  在这个例子裡,此 method 是一个 class level method。在物件建立后,在它上面唿叫 了 autorelease。在 main method 裡面,我从未在此物件上唿叫 release。

  这样行得通的塬因是:对任何 retain 而言,一定要唿叫一个 release 或 autorelease。物件的 retainCount 从 1 起跳 ,然后我在上面唿叫 1 次 autorelease,表示 1 - 1 = 0。当 autorelease pool 被释放时,它会计算所有物件上的 autorelease 唿叫次数,并且唿叫相同次数的 [obj release]。

  如同註解所说,不把那一行註解掉会造成分段错误(segment fault)。因为物件上已经唿叫过 autorelease,若再唿叫 release,在释放 autorelease pool 时会试图唿叫一个 nil 物件上的 dealloc,但这是不允许的。最后的算式会变为:1 (creation) - 1 (release) - 1 (autorelease) = -1

  管理大量暂时物件时,autorelease pool 可以被动态地产生。你需要做的只是建立一个 pool,执行一堆会建立大量动态物件的程式码,然后释放这个 pool。你可能会感到好奇,这表示可能同时有超过一个 autorelease pool 存在。

  


  Foundation framework classes

  Foundation framework 地位如同 C++ 的 Standard Template Library。不过 Objective-C 是真正的动态识别语言(dynamic types),所以不需要像 C++ 那样肥得可怕的样版(templates)。这个 framework 包含了物件组、网路、执行绪,还有更多好东西。

  NSArray

  1. main.m 
  2.  
  3. #import 
  4.  
  5. #import 
  6.  
  7. #import 
  8.  
  9. #import 
  10.  
  11. #import 
  12.  
  13. void print( NSArray *array ) { 
  14.  
  15. NSEnumerator *enumerator = [array objectEnumerator]; 
  16.  
  17. id obj; 
  18.  
  19. while ( obj = [enumerator nextObject] ) { 
  20.  
  21. printf( "%s ", [[obj description] cString] ); 
  22.  
  23. } 
  24.  
  25. } 
  26.  
  27. int main( int argc, const char *argv[] ) { 
  28.  
  29. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
  30.  
  31. NSArray *arr = [[NSArray alloc] initWithObjects: 
  32.  
  33. @"Me", @"Myself", @"I", nil]; 
  34.  
  35. NSMutableArray *mutable = [[NSMutableArray alloc] init]; 
  36.  
  37. // enumerate over items 
  38.  
  39. printf( "----static array " ); 
  40.  
  41. print( arr ); 
  42.  
  43. // add stuff 
  44.  
  45. [mutable addObject: @"One"]; 
  46.  
  47. [mutable addObject: @"Two"]; 
  48.  
  49. [mutable addObjectsFromArray: arr]; 
  50.  
  51. [mutable addObject: @"Three"]; 
  52.  
  53. // print em 
  54.  
  55. printf( "----mutable array " ); 
  56.  
  57. print( mutable ); 
  58.  
  59. // sort then print 
  60.  
  61. printf( "----sorted mutable array " ); 
  62.  
  63. [mutable sortUsingSelector: @selector( caseInsensitiveCompare: )]; 
  64.  
  65. print( mutable ); 
  66.  
  67. // free memory 
  68.  
  69. [arr release]; 
  70.  
  71. [mutable release]; 
  72.  
  73. [pool release]; 
  74.  
  75. return 0; 
  76.  
  77. } 

  output

  1. ----static array 
  2.  
  3. Me 
  4.  
  5. Myself 
  6.  
  7. I 
  8.  
  9. ----mutable array 
  10.  
  11. One 
  12.  
  13. Two 
  14.  
  15. Me 
  16.  
  17. Myself 
  18.  
  19. I 
  20.  
  21. Three 
  22.  
  23. ----sorted mutable array 
  24.  
  25. I 
  26.  
  27. Me 
  28.  
  29. Myself 
  30.  
  31. One 
  32.  
  33. Three 
  34.  
  35. Two 

  阵列有两种(通常是 Foundation classes 中最资料导向的部分),NSArray 跟 NSMutableArray,顾名思义,mutable(善变的)表示可以被改变,而 NSArray 则不行。这表示你可以製造一个 NSArray 但却不能改变它的长度。

  你可以用 Obj, Obj, Obj, ..., nil 为参数唿叫建构子来初始化一个阵列,其中 nil 表示结尾符号。

  排序(sorting)展示如何用 selector 来排序一个物件,这个 selector 告诉阵列用 NSString 的忽略大小写顺序来排序。如果你的物件有好几个排序方法,你可以使用这个 selector 来选择你想用的方法。

  在 print method 裡,我使用了 description method。它就像 Java 的 toString,会回传物件的 NSString 表示法。

  NSEnumerator 很像 Java 的列举系统。while ( obj = [array objectEnumerator] ) 行得通的理由是 objectEnumerator 会回传最后一个物件的 nil。在 C 裡 nil 通常代表 0,也就是 false。改用 ( ( obj = [array objectEnumerator] ) != nil ) 也许更好。

  NSDictionary

  1. main.m 
  2.  
  3. #import 
  4.  
  5. #import 
  6.  
  7. #import 
  8.  
  9. #import 
  10.  
  11. #import <<> 
  12.  
  13. #import 
  14.  
  15. void print( NSDictionary *map ) { 
  16.  
  17. NSEnumerator *enumerator = [map keyEnumerator]; 
  18.  
  19. id key; 
  20.  
  21. while ( key = [enumerator nextObject] ) { 
  22.  
  23. printf( "%s => %s ", 
  24.  
  25. [[key description] cString], 
  26.  
  27. [[[map objectForKey: key] description] cString] ); 
  28.  
  29. } 
  30.  
  31. } 
  32.  
  33. int main( int argc, const char *argv[] ) { 
  34.  
  35. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
  36.  
  37. NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys: 
  38.  
  39. @"one", [NSNumber numberWithInt: 1], 
  40.  
  41. @"two", [NSNumber numberWithInt: 2], 
  42.  
  43. @"three", [NSNumber numberWithInt: 3], 
  44.  
  45. nil]; 
  46.  
  47. NSMutableDictionary *mutable = [[NSMutableDictionary alloc] init]; 
  48.  
  49. // print dictionary 
  50.  
  51. printf( "----static dictionary " ); 
  52.  
  53. print( dictionary ); 
  54.  
  55. // add objects 
  56.  
  57. [mutable setObject: @"Tom" forKey: @"tom@"]; 
  58.  
  59. [mutable setObject: @"Bob" forKey: @"bob@" ]; 
  60.  
  61. // print mutable dictionary 
  62.  
  63. printf( "----mutable dictionary " ); 
  64.  
  65. print( mutable ); 
  66.  
  67. // free memory 
  68.  
  69. [dictionary release]; 
  70.  
  71. [mutable release]; 
  72.  
  73. [pool release]; 
  74.  
  75. return 0; 
  76.  
  77. } 
  78.  

  output

  1. ----static dictionary  
  2.   
  3. 1 => one  
  4.   
  5. 2 => two  
  6.   
  7. 3 => three  
  8.   
  9. ----mutable dictionary  
  10.   
  11. bob@ => Bob  
  12.   
  13. tom@ => Tom  

  优点与缺点

  优点

  Cateogies

  Posing

  动态识别

  指标计算

  弹性讯息传递

  不是一个过度复杂的 C 衍生语言

  可透过 Objective-C++ 与 C++ 结合

  缺点

  不支援命名空间

  不支援运算子多载(虽然这常常被视为一个优点,不过

  正确地使用运算子多载可以降低程式码复杂度)

  语言裡仍然有些讨厌的东西,不过不比 C++ 多。


阅读全文
扫码关注“ 多特资源库 ”
更多更全的软件资源下载
文章内容来源于网络,不代表本站立场,若侵犯到您的权益,可联系我们删除。(本站为非盈利性质网站)
玩家热搜

相关攻略

正在加载中
版权
版权说明

文章内容来源于网络,不代表本站立场,若侵犯到您的权益,可联系我们删除。(本站为非盈利性质网站)

电话:13918309914

QQ:1967830372

邮箱:[email protected]

toast