Objective-C 类与对象



Objective-C 编程语言的主要目的是为 C 编程语言添加面向对象特性,而类是支持面向对象编程的 Objective-C 的核心特性,通常被称为用户定义类型。

类用于指定对象的形态,它将数据表示和操作该数据的方法组合到一个整洁的包中。类中的数据和方法称为类的成员。

Objective-C 特性

  • 类在两个不同的部分中定义,即@interface@implementation

  • 几乎所有东西都以对象的形式存在。

  • 对象接收消息,对象通常被称为接收者。

  • 对象包含实例变量。

  • 对象和实例变量具有作用域。

  • 类隐藏对象的实现。

  • 属性用于在其他类中提供对类实例变量的访问。

Objective-C 类定义

定义类时,您定义了数据类型的蓝图。这实际上并没有定义任何数据,但它确实定义了类名的含义,即类对象将包含什么以及对这样的对象可以执行哪些操作。

类定义以关键字@interface开头,后跟接口(类)名称;以及由一对花括号括起来类体。在 Objective-C 中,所有类都派生自称为NSObject的基类。它是所有 Objective-C 类的超类。它提供基本方法,例如内存分配和初始化。例如,我们使用关键字class定义 Box 数据类型,如下所示:

@interface Box:NSObject {
   //Instance variables
   double length;    // Length of a box
   double breadth;   // Breadth of a box
}
@property(nonatomic, readwrite) double height;  // Property

@end

实例变量是私有的,只能在类实现内部访问。

分配和初始化 Objective-C 对象

类为对象提供蓝图,因此基本上对象是从类创建的。我们使用与声明基本类型变量完全相同的声明来声明类的对象。以下语句声明了两个 Box 类的对象:

Box box1 = [[Box alloc]init];     // Create box1 object of type Box
Box box2 = [[Box alloc]init];     // Create box2 object of type Box

box1 和 box2 这两个对象都将拥有自己的数据成员副本。

访问数据成员

可以使用直接成员访问运算符 (.) 访问类对象的属性。让我们尝试以下示例来说明:

#import <Foundation/Foundation.h>

@interface Box:NSObject {
   double length;    // Length of a box
   double breadth;   // Breadth of a box
   double height;    // Height of a box
}

@property(nonatomic, readwrite) double height;  // Property
-(double) volume;
@end

@implementation Box

@synthesize height; 

-(id)init {
   self = [super init];
   length = 1.0;
   breadth = 1.0;
   return self;
}

-(double) volume {
   return length*breadth*height;
}

@end

int main() {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];    
   Box *box1 = [[Box alloc]init];    // Create box1 object of type Box
   Box *box2 = [[Box alloc]init];    // Create box2 object of type Box

   double volume = 0.0;             // Store the volume of a box here
 
   // box 1 specification
   box1.height = 5.0; 

   // box 2 specification
   box2.height = 10.0;
  
   // volume of box 1
   volume = [box1 volume];
   NSLog(@"Volume of Box1 : %f", volume);
   
   // volume of box 2
   volume = [box2 volume];
   NSLog(@"Volume of Box2 : %f", volume);
   
   [pool drain];
   return 0;
}

编译并执行上述代码时,将产生以下结果:

2013-09-22 21:25:33.314 ClassAndObjects[387:303] Volume of Box1 : 5.000000
2013-09-22 21:25:33.316 ClassAndObjects[387:303] Volume of Box2 : 10.000000

属性

在 Objective-C 中引入属性是为了确保可以在类外部访问类的实例变量。

属性的各个部分如下所示。
  • 属性以@property开头,这是一个关键字

  • 后面跟着访问说明符,即 nonatomic 或 atomic、readwrite 或 readonly 以及 strong、unsafe_unretained 或 weak。这根据变量的类型而有所不同。对于任何指针类型,我们可以使用 strong、unsafe_unretained 或 weak。类似地,对于其他类型,我们可以使用 readwrite 或 readonly。

  • 后面跟着变量的数据类型。

  • 最后,我们有一个以分号结尾的属性名称。

  • 我们可以在实现类中添加 synthesize 语句。但在最新的 XCode 中,合成部分由 XCode 处理,您无需包含 synthesize 语句。

只有使用属性,我们才能访问类的实例变量。实际上,内部为属性创建了 getter 和 setter 方法。

例如,假设我们有一个属性@property (nonatomic ,readonly ) BOOL isDone。在后台,创建了如下所示的 setter 和 getter。

-(void)setIsDone(BOOL)isDone;
-(BOOL)isDone;
广告

© . All rights reserved.