Objective-C抽象类的实现

这篇博客探讨了如何在Objective-C中使用抽象类来实现下载功能。通过定义一个DownloaderProtocol协议,创建抽象类AbstractDownloader,以及具体的实现类如ImageDownloader,详细阐述了抽象类在接口设计和实现过程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下载功能为例:

1.协议
DownloaderProtocol.h

    #import <Foundation/Foundation.h>  

    @protocol DownloaderProtocol <NSObject>  
    @required    
    - (BOOL)checkDownloader;  
    - (void)startDownload:(id)url;  
    - (void)stopDownload;  
    - (void)deleteAllDownloadFile;

    //可以使用@optional定义"可选的"接口
    //略

    @end  

2.抽象类
AbstractDownloader.h

    #import <Foundation/Foundation.h>  
    #import "DownloaderProtocol.h"  

    //遵循协议!!  
    @interface AbstractDownloader : NSObject <DownloaderProtocol>  

    //自己的方法  
    - (void)setDownloadUrl:(NSString *)url;  
    @end  

AbstractDownloader.m

#import "AbstractDownloader.h"  

#define AbstractMethodNotImplemented() \  
@throw [NSException exceptionWithName:NSInternalInconsistencyException \  
reason:[NSString stringWithFormat:@"You must override %@ in a subclass.", NSStringFromSelector(_cmd)] \  
userInfo:nil]  


@implementation AbstractDownloader  
- (instancetype)init  
{  
    NSAssert(![self isMemberOfClass:[AbstractDownloader class]], @"AbstractDownloader is an abstract class, you should not instantiate it directly.");  

    return [super init];  
}  

//让子类自己去实现  如果没有实现则此处抛出异常
- (BOOL)checkDownloader  
{  
    AbstractMethodNotImplemented();  
}  

- (void)startDownload:(id)url  
{  
    AbstractMethodNotImplemented();  
}  

- (void)stopDownload  
{  
    AbstractMethodNotImplemented();  
}  

- (void)deleteAllDownloadFile  
{  
    AbstractMethodNotImplemented();  
}  

  //自己的方法
- (void)setDownloadUrl:(NSString *)url  
{  
    NSLog(@"AbstractDownloader's url = %@", url);  
}  

3.具体实现类

ImageDownloader.h

    #import "AbstractDownloader.h"  

    @interface ImageDownloader : AbstractDownloader  

    @end  

ImageDownloader.m

    #import "ImageDownloader.h"  

    @implementation ImageDownloader  

    - (BOOL)checkDownloader  
    {  
        NSLog(@"ImageDownloader checkDownloader...");  

        return YES;  
    }  

    - (void)startDownload:(id)url  
    {  
        NSLog(@"ImageDownloader startDownload...");  
    }  

    - (void)stopDownload  
    {  
        NSLog(@"ImageDownloader stopDownload...");  
    }  

    - (void)deleteAllDownloadFile  
    {  
        NSLog(@"ImageDownloader deleteAllDownloadFile...");  
    }  

    @end  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值