@class主要是在h(头文件)中使用。主要的作用是告诉编译器:我要在本类中,使用另一个类。
假设要在Aonauly类中使用Action类,使用@class实现过程如下:
首先是定义Action
1,Action.h代码如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#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
|
#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
|
#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;
-(
void
) setAction:(Action *) ac;
@end
|
注意:
![01.png wKioL1mzYADhXV7kAADPNyY3umY535.png-wh_50]()
在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
|
#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];
}
-(
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
|
#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);
myAonaufly._a = 3;
myAonaufly._b = 5;
sum = [myAonaufly sum:myAonaufly._a :myAonaufly._b];
NSLog(@
" this %i + %i value is : %i "
, myAonaufly._a , myAonaufly._b , sum);
Action *myAction;
myAction = [[Action alloc] init];
[myAonaufly setAction:myAction];
[myAonaufly.action eat];
}
return
0;
}
|
结果如下:
![02.png wKioL1mzYXnhBo9ZAABZNIU3ZRE985.png-wh_50]()
[myAonaufly.action eat] 注意是调用Aonaufly 中的Action的eat方法
本文转自Aonaufly51CTO博客,原文链接:http://blog.51cto.com/aonaufly/1963904 ,如需转载请自行联系原作者