OC实现一个函数多返回值的两种途径

在OC语言中如果你期望一个函数有多个不同类型的返回值,是不可能的。

eg: 代码写成这样,是不可能的

-(Bool,NSAttributedString*)getTailReplacedAttributedStringWithWidth:(double)width;


但是可以通过其他的途径来解决这个问题

一、对多返回值进行包装

将多个返回值,封装成一个数据模型,或者放到容器里面如NSdictionary、NSArray

-(NSDictionary*)getTailReplacedAttributedStringWithWidth:(double)width

{

//计算替换字符串的size,如果size.width>width,不进行末尾字符串替换

    NSMutableDictionary *resultDict = [[NSMutableDictionary alloc]initWithCapacity:0];

    NSNumber*numberObject = [[NSNumberalloc]initWithBool:YES];

    [resultDictsetObject:numberObjectforKey:@"numberKey"];

    NSAttributedString * attributedString = [[NSAttributedString alloc]initWithString:@"属性字符串"];

    [resultDictsetObject:attributedStringforKey:@"attributedStringKey"];

    return resultDict;

}

二、使用block

block严格意义上不能算上是返回值,但是能实现多返回值的效果

-(void)getTailReplacedAttributedStringWithWidth:(double)width

                                       complete:(void(^)(BOOLflag,NSAttributedString*resultString))completeBlock{

    NSMutableAttributedString * resultAttributedString = [[NSMutableAttributedString alloc]init];

    if(completeBlock) {

        completeBlock(YES,resultAttributedString);

    }

}

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