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];//判断两个时间相等