OC与C结构体

2017-09-14  本文已影响15人  George2016

结构体一般都只有数据成员,而没有函数成员。也就是像int、double这样的数据类型,函数需要单独定义。

所以想要C结构体中绑定一个函数就需要用到指针函数。

UserInfo.h

typedef struct _user {
    int year;
    int month;
    char *name;
    int(*add)(int a, int b);
    UILabel*(*label)(char *title);
}User;

static int fun_add(int a, int b) {
    return a+b;
}

static UILabel *label(char *title) {
    
    UILabel *label = [UILabel new];
    
    label.text = [NSString stringWithCString:title encoding:NSUTF8StringEncoding];
    
    label.backgroundColor = [UIColor greenColor];
    
    return label;
}

@interface UserInfo : NSObject

+(User)sharedInstance;

@end

UserInfo.m

@implementation UserInfo
+(User)sharedInstance {
    struct _user obj = {
        2,
        5,
        "张三",
        .add = fun_add,
        .label = label,
    };
    return obj;
}
@end

在控制器中的使用

User demo = [UserInfo sharedInstance];
int res = demo.add(1, 3);
NSLog(@"res=%d", res);
NSLog(@"year=%d", demo.year);
NSLog(@"name=%s", demo.name);

UILabel *label = demo.label("中国欢迎你");
label.frame = CGRectMake(300, 100, 300, 200);
[self.view addSubview:label];
上一篇 下一篇

猜你喜欢

热点阅读