---
title: " Object-C学习（二）"
author: "supermind"
date: "2011-07-14T11:28:09Z"
tags: []
categories: ["移动开发"]
slug: "object-c"
draft: false
lastmod: "2011-07-14T11:30:28Z"
id: 1124158
url: "https://supermind.iteye.com/blog/1124158"
---

引用：http://blog.csdn.net/huanglx1984/article/details/4293113


上次说了Objective C是一种挺好的面向对象的语言。那么我们今天就来看看Objective C中的一些面向对象的特性吧。

 

构造函数 (constructor)

其实我觉得在Objective C中，这个名字并不算很恰当，可能叫做“初始化函数”比较合适一些吧。

因为这个函数其实就是一个普通的函数，和C++与Java中对构造函数的特殊待遇不同。

举个例子：




@interface Sample : NSObject { 

    int a;


} 

- (Sample*) initWithIntValue: (int)aa; 

- (void) setA : (int) aa; 

- (void) print;


@end 




@implementation Sample 

- (Sample*) initWithIntValue: (int)aa { 

     if( self =  ) { 

         ;


     } 

     return self;


} 

// setA 和 print 的实现参见上一篇 


@end 

 

其实，initWithIntValue 就是所谓的“构造函数”。我们在使用的时候，还是需要先调用父类NSObject中的alloc方法（注：alloc方法是一个static的方法，它是被“+”修饰的， 参见上篇关于函数声明的介绍）： 

Sample* smp =  initWithIntValue:1]; 

 

对构造函数的几个说明：

1） 返回值一定要是类的指针

2） 一定要先调用父类NSObject的init函数，因为在Objective C中所有的类都是从NSObject继承来的

3） 检查init返回的值是否有效

4） self : 这是Objective C的一个关键字，概念上和C++与Java中的this 一样

 


在面向对象程序设计中，大家一定很熟悉访问限制的概念，也就是C++和Java中的public, protected, private，在Objective C中也有类似的东西

#import <Foundation/NSObject.h>
@interface AccessExample: NSObject {
@public
    int publicVar;
@protected
    int protectedVar;
@private
    int privateVar;
}
@end 

 

没错，就是挺简单的。

 


还记得之前说的Objective C中的静态方法么(static messages)？下面我们来看一个例子：

 

// ClassA.h 

#import <Foundation/NSObject.h>
static int count; 

@interface ClassA:NSObject
+ (int) getCount;
+ (void) initialize;
@end 

 

// Implementation
@implementation ClassA
- (id) init {
    self = ;
    count++;
    return self;
}
+ (int) getCount {
    return count;
}
+ (void) initialize {
    count = 0;
}
@end 

 

static int count; 

在C++中，还记得怎么声明静态变量么？

view plaincopy to clipboardprint?class A {  
public:  
   A();  
   ~A();  
protected:  
   static int a;  
}  
static int A::a = 0;  
class A {
public:
   A();
   ~A();
protected:
   static int a;
}
static int A::a = 0; 

但是在Objective C中，所谓类的静态变量其实可以理解为一个全局的静态变量，因为它并没有被放在@interface的定义里面。

接下来，getCount 和initialize 是两个静态方法。getCount 用于返回当前对象的个数，而initialize 用于清空对象的计数。

但是在Implementation中，为什么会有init 这个方法呢？

是的，这里可以理解为，我们重载了NSObject 中的init 方法：仅增加了一个功能，就是计数。我们不需要在头文件中声明init ，因为我们继承了NSObject。

 

如何使用这个类呢：

int main( int argc, char* argv ) {
    ;


    ClassA *c1 =  init];
    ClassA *c2 =  init];     

    printf( "ClassA count: %i/n",  ); 

    ... ...  
} 

 

读者自己试一试实现自己的release方法吧:)

未完待续~~