iOS筆記—SEL

對於SEL的簡單使用

//
//  main.m
//  selector
//
//  Created by hhg on 15-6-17.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Person.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *p = [[Person alloc] init];
        SEL k = @selector(jump);
        [p eat];
        [p mySelector:k];
    }
    return 0;
}

下面是個Person類

//
//  Person.h
//  selector
//
//  Created by hhg on 15-6-17.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Person : NSObject

- (void)eat;
- (void)jump;

- (void)mySelector:(SEL)k;

@end
//
//  Person.m
//  selector
//
//  Created by hhg on 15-6-17.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import "Person.h"

@implementation Person

- (void)eat {

    NSLog(@"我正在喫飯....請勿打擾");

}

- (void)jump {
    NSLog(@"我正在跳躍....請勿打擾");
}

- (void)mySelector:(SEL)k {

    IMP imp = [self methodForSelector:k];

    void (*func)(id, SEL) = (void *)imp;

    func(self, k);
}

@end
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章