Objective-C @class
@class主要是在h(头文件)中使用。主要的作用是告诉编译器:我要在本类中,使用另一个类。
假设要在Aonauly类中使用Action类,使用@class实现过程如下:
首先是定义Action
1,Action.h代码如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//
// Action.h
// Ainy_Console
//
// Created by Apple on 2017/9/9.
// Copyright 2017年 Apple. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Action : NSObject
-(
void
) eat;
//声明吃的方法
@end
|
2,Action.m代码如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
//
// Action.m
// Ainy_Console
//
// Created by Apple on 2017/9/9.
// Copyright 2017年 Apple. All rights reserved.
//
#import "Action.h"
@implementation Action
/**
*实现吃的方法
*/
-(
void
) eat
{
NSLog(@
"I love eat apple"
);
}
@end
|
好 , 我们在Aonaufly类中申明对Action的引用
1,aonaufly.h代码如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
//
// Aonaufly.h
// Ainy_Console
//
// Created by Apple on 2017/9/7.
// Copyright 2017年 Apple. All rights reserved.
//
#import <Foundation/Foundation.h>
@
class
Action;
@interface Aonaufly : NSObject
@property
int
_a , _b;
-(
int
) sum_one : (
int
) c sum_b : (
int
) d;
//带参数名的方法
-(
int
) sum :(
int
) i : (
int
) j;
//不带参数名的方法
-(Action *) action;
//申明了自己定义的一个类Action
-(
void
) setAction:(Action *) ac;
@end
|
注意:
在H文件中必需要编译器知道Action到底是什么 , 那个@class就是干这个的。
2,Aonaufly.m代码如下:
|
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
31
32
33
34
|
//
// Aonaufly.m
// Ainy_Console
//
// Created by Apple on 2017/9/7.
// Copyright 2017年 Apple. All rights reserved.
//
#import "Aonaufly.h"
#import "Action.h"
@implementation Aonaufly
{
Action * action;
}
@synthesize _a , _b;
-(
int
) sum_one:(
int
)c sum_b:(
int
) d
{
return
[self sum:c :d];
//调用本类的方法sum
}
-(
int
) sum:(
int
)i :(
int
)j
{
return
i + j;
}
-(
void
) setAction:(Action *)ac
{
action = ac;
}
-(Action *) action
{
return
action;
}
@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
31
32
|
//
// main.m
// Ainy_Console
//
// Created by Apple on 2017/9/6.
// Copyright 2017年 Apple. All rights reserved.
//
#import "Aonaufly.h"
#import "Action.h"
int
main(
int
argc,
const
char
* argv[]) {
@autoreleasepool {
Aonaufly *myAonaufly;
myAonaufly = [[Aonaufly alloc] init];
int
sum = [ myAonaufly sum_one:1 sum_b:2];
//调用方法(带参数)
NSLog(@
"this is 1 + 2 SUM : %i"
, sum);
//为属性 _a , _b 赋值
myAonaufly._a = 3;
myAonaufly._b = 5;
//调用不带参数名的sum方法如下
sum = [myAonaufly sum:myAonaufly._a :myAonaufly._b];
NSLog(@
" this %i + %i value is : %i "
, myAonaufly._a , myAonaufly._b , sum);
//对于@class
Action *myAction;
myAction = [[Action alloc] init];
[myAonaufly setAction:myAction];
[myAonaufly.action eat];
//调用Aoanufly中Action的eat方法
}
return
0;
}
|
结果如下:
[myAonaufly.action eat] 注意是调用Aonaufly 中的Action的eat方法

