在 iOS中可以直接调用 某个对象的实例方法
一种是performSelector:withObject:
再一种就是NSInvocation
第一种方式比较简单,能完成简单的调用。但是对于>2个的参数或者有返回值的处理,那就需要做些额外工作才能搞定。那么在这种情况下,我们就可以使用NSInvocation来进行这些相对复杂的操作
下面是一些代码.
CurrentDate.h
//
//
//
//
#import <Foundation/Foundation.h>
@interface CurrentDate : NSObject {
}
- (NSString *)stringForDate: (NSDate *)date usingFormatter: (NSDateFormatter *)formatter withID:(NSString *)userID;
- (NSString *)getCurData;
@end
#import "CurrentDate.h"
@implementation CurrentDate
- (NSString *)stringForDate: (NSDate *)date usingFormatter: (NSDateFormatter *)formatter withID:(NSString *)userID
{
}
- (NSString *)getCurData
{
NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy年MM月dd日 hh:mm:ss"];
return [dateFormat stringFromDate:[NSDate date]];
}
@end
下面函数是类的实例方法调用带参数的,
- (void)instanceMethodCall
{
//performSelector调用
CurrentDate * currentDateClassObject = [[CurrentDate alloc] init];
SEL mySelector = @selector(getCurData);
NSString * currentDate = [currentDateClassObject performSelector:mySelector withObject:nil];
NSLog(@"performSelector 调用返回日期:%@",currentDate);
currentDate = nil;
//NSInvocation调用
NSMethodSignature * sig = [[CurrentDate class]instanceMethodSignatureF
NSInvocation * myInvocation = [NSInvocation invocationWithMethodSign
[myInvocation setTarget:currentDateClassObject];// 设置目的实例
[myInvocation setSelector:mySelector];// 设立方法
[myInvocation invoke]; //调用方法
NSLog(@"NSInvocation 调用返回日期:%@",currentDate);
currentDate = nil;
//原始调用多个参数返回数据
[dateFormat setDateFormat:@"yyyy年MM月dd日 hh:mm:ss"];
currentDate = [currentDateClassObject stringForDate: [NSDate date] usingFormatter: dateFormatwithID:@"http://blog.sina.com.cn/zing1230"];
[dateFormatter setDateFormat:@"yyyy年MM月dd日 hh:mm:ss"];
NSString * userID = @"test";
[myInvocation setArgument:&userID atIndex: 4];
[myInvocation retainArguments]; //retain 所有参数,防止参数被释放dealloc
}
参考内容
http://www.cnblogs.com/chenjunbiao/archive/2011/04/20/2022197.html
http://blog.csdn.net/cancer1617/article/details/6855484
转载:http://blog.sina.com.cn/s/blog_677089db01013w48.html