0%

子类对象之间的强转

#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–