子类对象之间的强转

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容