导航

Objective-C语言学习(一)

Posted on 2013-01-06 00:40  ADaii  阅读(281)  评论(0编辑  收藏  举报

主要内容

1.类的声明

2.函数/消息的定义的方法

3.字段的作用域

4.使用Xcode建立项目

-----------我是分割线------------

1.类的声明<Dog.h>

1 #import <Foundation/Foundation.h>
2 @interface Dog : NSObject
3 {}
4 @end

2.类的实现<Dog.m>

1 #import "Dog.h"
2 @implementation Dog
3 
4 @end

3.创建/销毁OC对象

创建对象

  Dog *dog = [Dog alloc];

初始化构造函数

  [dog init];

销毁对象

  [dog release]; 

4.类中字段和函数

 1 @interface Dog : NSObject
 2 { 
 3 //变量定义
 4 int age;   
 5 }
 6 
 7 //定义函数
 8 - (void) setAge:(int)newAge;
 9 
10 @end

 5.变量作用域申明

文件 Dog.h

 1 @interface Dog : NSObject
 2 {
 3     @public
 4         int age;
 5     @protected
 6         int ID;
 7     @private
 8         float price;
 9 }
10 @end

 6.类的声明

Dog *myDog;

类声明 <Dog.h>

 1 #import <Foundation/Foundation.h>
 2 @interface Dog : NSObject
 3 {
 4     int age;
 5 }
 6 - (id) init;
 7 - (id) initWithAge:(int)newAge;
 8 - (int) getAge;
 9 - (void) setAge:(int)newAge;
10 @end

 

 7.类的实现 <Dog.m>

 1 #import "Dog.h"
 2 @implementation Dog
 3 - (id) init
 4 {
 5     return [self initWithAge:10];
 6 }
 7 - (id) initWithAge:(int)newAge
 8 {
 9     self = [super init];
10     if(self)
11     {
12         age = newAge;
13     }
14     return self;
15 } 

OC在 .h 头文件定义的所有函数都是public类型

OC通过Categories来实现函数私有

 

8.Xcode建立项目

  1.新建Xcode项目

  2.点击OS X的Command Line Tool

  3.填写项目名称

  4.选择新建文件

  5.选择Object-C class类型文件

  6.填写文件名称

  7.建立完成