iOS指针回调函数

//
//  main.m
//  LessonReturnFunPointer
//
//  Created by laouhn on 15/7/29.
//  Copyright (c) 2015年 池海涛. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Function.h"
int main(int argc, const char * argv[]) {
 
    //定义两个函数,求最大值,最小值,求和
//    int value = max(3, 5);
//    printf("value = %d 
", value);
//
    
    //char s[20] = "d";
    //scanf("%s",&s[20]);
    //shuruzhilin(3,5,(p)s);
    while (1) {
        printf("请输入想要执行的操作:max 求最大值,min 最小值,sum 最大值");
        char str[20] = {0};
        scanf("%s", str);
        int value = getValueForString(3, 5, str);
        printf("value = %d
",value);

    }
   
    return 0;
}

Function.h

//
//  Function.h
//  LessonReturnFunPointer
//
//  Created by laouhn on 15/7/29.
//  Copyright (c) 2015年 池海涛. All rights reserved.
//

#import <Foundation/Foundation.h>


//最大值
typedef int (*FUNC)(int, int);
int max(int a, int b);
int min(int a, int b);
int sum(int a, int b);

void shuruzhilin(int,int,FUNC p);
typedef int (*PFUN)(int,int);
struct nameFunctionPair {
    char name[20];
    PFUN function;
    
};
typedef struct nameFunctionPair NameFunctionPair;

//分析:根据需求,首先用于匹配的表(印射表) ---结构体数组,那么接下来,这个表应该创建在哪?---Funtion.m文件中
int getValueForString(int a,int b, char str[]);
PFUN getFunctionByName(char *string);

Function.m

//
//  Function.m
//  LessonReturnFunPointer
//
//  Created by laouhn on 15/7/29.
//  Copyright (c) 2015年 池海涛. All rights reserved.
//

#import "Function.h"


int max(int a, int b)
{
    return a > b ? a : b;
}
int min(int a, int b)
{
    return a > b ? b : a;
}
int sum(int a, int b)
{
    return a + b;
}

void shuruzhilin(int a,int b,FUNC p)
{
    int c = p(a,b);
    printf("%d ",c);
}

NameFunctionPair funpair[] = {
    {"max",max},
    {"min",min},
    {"sum",sum}
};
//该函数能够帮我们实现的目标:更据字符串str 匹配到相应的函数,然后,进行运算,计算两个参数 a ,b相应的值,进行返回
int getValueForString(int a,int b, char str[])
{
    
   PFUN func = getFunctionByName(str);//此时保存的是函数指针
    return func(a,b);
}

PFUN getFunctionByName(char *string){
    
    
    for (int i = 0; i < sizeof(funpair) / sizeof(funpair[0]); i++) {
        if (strcmp(string, funpair[i].name)==0) {
            return  funpair[i].function;
        }
    }
    return max;//当印射没有返回值,就返回max函数
    
}
原文地址:https://www.cnblogs.com/wohaoxue/p/4688149.html