iOS基础学习

Objective-C基础学习之typedef和Block

2017-10-13  本文已影响90人  WenJim

1.函数指针回顾

int sum(int value1, int value2)
{
    return value1 + value2;
}

int minus(int value1, int value2)
{
    return value1 - value2;
}

int main(int argc, const char * argv[]) {
    int (*sumP) (int, int) = sum;
    int res = sumP(10, 20);
    NSLog(@"res = %i", res);

    int (*minusP) (int , int) = minus;
    res = minusP(10, 20);
    NSLog(@"res = %i", res);
    return 0;
}
typedef int (*calculate) (int, int);
int main(int argc, const char * argv[]) {
    calculate sumP = sum;
    int res = sumP(10, 20);
    NSLog(@"res = %i", res);
    calculate minusP = minus;
    res = minusP(10, 20);
    NSLog(@"res = %i", res);
    return 0;
}

2.block和typedef

int main(int argc, const char * argv[]) {
  int (^sumBlock) (int, int) = ^(int value1, int value2){
      return value1 + value2;
  };
  int res = sumBlock(10 , 20);
  NSLog(@"res = %i", res);

  int (^minusBlock) (int, int) = ^(int value1, int value2){
      return value1 - value2;
  };
  res = minusBlock(10 , 20);
  NSLog(@"res = %i", res);
  return 0;
}
int main(int argc, const char * argv[]) {
    calculateBlock sumBlock = ^(int value1, int value2){
        return value1 + value2;
    };
    int res = sumBlock(10, 20);
    NSLog(@"res = %i", res);
    calculateBlock minusBlock = ^(int value1, int value2){
        return value1 - value2;
    };
    res = minusBlock(10, 20);
    NSLog(@"res = %i", res);

    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读