OC高级(一)

Block

块语法,匿名函数。C++、JS、Swift等语言中有类似语法,叫做闭包。Block语法和函数指针很类似。

    //无返回值无参
    void (^firstBlock)() = ^(){
        NSLog(@"帅");
    };
    firstBlock();

    //有返回值有参
    int (^forthBlock)(int ,int ) = ^(int num1,int num2){
        return num1 + num2;
    };
    NSLog(@"%d",forthBlock(10,20));

typedef int (^BlockType)(int);

    BlockType b = ^(int num1){
        return num1;
    };
    NSLog(@"%d",b(1));

Block块内部可使用方法内变量,但不可修改。可在block外使用_block修饰使其可修改。有使用和修改全局变量的权限。通常当参数来使用。

Block数组排序

<pre name="code" class="objc">- (instancetype)init
{
if (self = [super init]){
_numArr = [NSMutableArray arrayWithObjects:@"g",@"mc",@"m",@"w", nil];
}
return self;
}
- (void)sort:(sortCompare)sc
{
for (int i = 0;i < [_numArr count] - 1; i ++){
for (int j = 0; j < [_numArr count] - i - 1; j ++) {
if (sc(_numArr[j],_numArr[j + 1])){
// NSObject *c = _numArr[j];
// _numArr[j] = _numArr[j + 1];
// _numArr[j + 1] = c;
[_numArr exchangeObjectAtIndex:j withObjectAtIndex:j + 1];//调换数组
}
}
}
NSLog(@"%@",_numArr);
}


    [p sort:^BOOL(NSString *s1, NSString *s2) {
        if ([s1 compare:s2] == NSOrderedAscending){
            return YES;
        }
        return NO;
    }];

字面量:Literals,一种简易表示值的方法。简化创建过程。

字面量创建的对象是便利构造的,且是不可变的。

    NSString *str = @"Hello";
    NSArray *arr = @[@"a",@"b",@"c"];
    //arr[1];
    NSDictionary *dict = @{@"1":@"a",@"2":@"b",@"3":@"c"};

NSDate

    NSDate *nowDate = [[NSDate alloc]init];//初始化,获取时间为0时区当前时间
    NSDate *nowDate1 = [NSDate date];
    
    NSDate *date = [nowDate dateByAddingTimeInterval:8 * 60];//添加时间
    NSDateFormatter *df = [[NSDateFormatter alloc] init];//设置时间格式
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dStr = [df stringFromDate:date];//时间转换为字符串
    NSDate *d1 = [df dateFromString:dStr];//字符串转换为时间
    NSTimeInterval ti = [date timeIntervalSinceNow];//与当前时间的时间差
    NSTimeInterval ti1 = [date timeIntervalSinceDate:nowDate];//两个时间的时间差
    
    BOOL bd = [date isEqualToDate:nowDate];//判断两个时间相等











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值