主要介绍Object-C中类、变量、方法的实际使用

一、这里给一个类的声明 Student.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@interface Student : NSObject {
int age;
@public
int no;
int score;
@protected
float height;
@private
float weight;
}
- (int)age;
- (void)setAge:(int)newAge;
- (void)setAge:(int)newAge andHeight:(float)newHeight;
- (id)initWithAge:(int)newAge;
- (id) initWith;
@end

@interface 类的声明
:NSObject 继承NSObject类,自己建的类一般都继承NSObject
@public,@protected,@private 变量作用域,在Object-C中没有包的概念,因此作用域只有三种,变量没有设置作用域时默认为protected,声明变量需要在大括号里,而声明方法不需要
- 声明方法为动态方法,即对象的方法
+ 声明方法为静态方法,即类的方法
方法的声明规则是:
(返回类型)方法名; //无参数方法声明
(返回类型)方法名:(参数类型)参数名; //有一个参数方法声明
(返回类型)方法名:(参数类型)参数名 方法名二:(参数类型)参数名; //有两个参数的方法声明

需要注意的是
1、无论是返回类型还是参数类型都需要用括号括起来;
2、带参的方法中每个参数前都有一个方法名,用以描述参数的意义,多个方法名构成一个方法;
3、参数和方法名之间有一个冒号,一个参数对应一个冒号,没有参数不需要冒号,但是有一个方法名;

@end 类的结束

二、类的实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#import “Student.h"
@implementation Student
- (int)age{
return age;
}
- (void)setAge:(int)newAge{
age=newAge;
}
- (void)setAge:(int)newAge andHeight:(float)newHeight{
age=newAge;
height=newHeight;
}
- (id)initWithAge:(int)newAge{
self=[super init];
if(self=[super init]){
age=newAge;
}
return self;
}
- (id) initWith{
self=[super init];
return self;
}
@end

#import “Student.h” 导入头文件,用以实现声明的方法,C语言中有#include,同样是导入头文件,但是#import更智能,可以自动防止同一个头文件被包含多次

方法的实现很简单,照用.h头文件中声明的方法,去掉分号,在方法后打上大括号,在括号里编写实现语句。

三、对类的实例化和变量、方法的调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#import “Search.h"
int main(int argc, char * argv[]) {
Student *student = [[Student alloc] init];
student ->no=10;
[student setAge:28 andHeight:1.88f];
int no=search->no;
student.age=27; //等价于[student setAge:27];
int age= student.age; //等价于[student getAge];
NSLog(@"no is %i and age is %i", no, age);
return 0;
}

#import “Student.h” 导入头文件,用以使用该类
方法的调用规则是 [类 静态方法] 或[对象 动态方法]
变量的调用规则是 对象->变量

[Student alloc] 调用类的静态方法alloc分配内存
init 调用student对象进行初始化

. 点语法在Object-C中可用以代替get方法和set方法,当接收赋值时是set方法,取值时是get方法,即student.age调用的还是setAge或getAge方法。

文章目录