iOS哨兵参数&&内联函数

2018-05-22  本文已影响0人  Fisher123

1. iOS传递不定长多个参数

在iOS要实现不定参数的函数,有一个方案是用C/C++中的va_list、va_start、va_arg、va_end来实现。这样实现需要一个哨兵参数,就是调用方法是最后必须要加一个nil或者0的参数,该参数就称为哨兵参数 for example :

- (void)mutableParamList:(NSString *)fistPara, ... {
    va_list arguments;
    id eachObject;
    if (fistPara) {
        NSLog(@"%@",fistPara);
        va_start(arguments, fistPara);
        while ((eachObject = va_arg(arguments, id))) {
        NSLog(@"%@",eachObject);
     }
        va_end(arguments);
    }
}

调用:

[self mutableParamList:@"aaaa",@"bbbb",@"cccc",@"dddd",nil];

2. iOS内联函数使用(关键字 NS_INLINE)

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

NS_INLINE void tipWithMessage(NSString *message) {
    dispatch_async(dispatch_get_main_queue(), ^{
    UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alerView show];
    [alerView performSelector:@selector(dismissWithClickedButtonIndex:animated:) withObject:@[@0, @1] afterDelay:0.9];        
    });    
}

对于调用也是非常的简单,在-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 方法中,调用弹窗函数:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    tipWithMessage(@"世界, 你好!");
}
效果图
上一篇 下一篇

猜你喜欢

热点阅读