子类对象之间的强转

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#import <Foundation/Foundation.h>

@interface Tom : NSObject
@property (nonatomic,copy) NSString *name;
@property (nonatomic) NSInteger age;
@end

@implementation Tom
- (instancetype)initWithName:(NSString *)name andAge:(NSInteger)age {
if (self = [self init]) {
self.name = name;
self.age =age;
}
return self;
}
@end

@interface Jerry : NSObject
@property (nonatomic) NSString *name;
@property (nonatomic) NSInteger age;
@end

@implementation Jerry
- (instancetype)initWithName:(NSString *)name andAge:(NSInteger)age {
if (self = [self init]) {
self.name = name;
self.age =age;
}
return self;
}
@end

@interface Test : NSObject
@end

@implementation Test
+ (void)showName:(Tom *)tom {
NSLog(@"%@",tom.name);
}
+ (void)showNameWithKVC:(NSObject *)obj{
NSString *name = [obj valueForKey:@"name"];
NSLog(@"%@",name);
}
@end

int main(int argc, const char * argv[]) {
@autoreleasepool {
Tom *tom = [[Tom alloc]initWithName:@"Tom" andAge:10];
Jerry *jerry = [[Jerry alloc]initWithName:@"Jerry" andAge:10];

//可以通过强转的方式
[Test showName:(Tom *)jerry];
[Test showName:tom];

//也可以通过KVC
[Test showNameWithKVC:jerry];
[Test showNameWithKVC:tom];

}
return 0;
}

–EOF–