2013년 4월 13일 토요일

객체를 생성하지 않고도 instance method를 호출하게 해주는 instanceMethodForSelector

NSObject를 상속받은 클래스의 인스턴스를 생성하지 않고도 모든 인스턴스 메소드를 호출할 수 있다.
+ (IMP)instanceMethodForSelector:(SEL)aSelector 는 aSelector함수를 구현한 어드레스(함수포인터)를 반환한다.

아래 소스는 NSOjbect의 클래스 메소드 instanceMethodForSelector를 어떻게 사용하는지에 대한 예제이다.

// Utility.h
@interface Utility : NSObject
{
}

+ (void)showLoadingView;



// Utility.m
static UIView *loadingView=nil;
static UIView *loadingContainerView=nil;
static bool isShowActivityIndicator = false;

+ (void)showLoadingView
{
IMP func = [Utility instanceMethodForSelector:@selector(performSelector:withObject:afterDelay:)];
func(self, @selector(performSelector:withObject:afterDelay:), @selector(doShowLoadingView),nil,0);
}

+ (void)doShowLoadingView
{
UIWindow *mainWindow = [[UIApplication sharedApplication].delegate window];

if (loadingView == nil) {

loadingContainerView = [[UIView alloc] initWithFrame:mainWindow.frame];
loadingView = [[UIView alloc] initWithFrame:CGRectMake(mainWindow.center.x-70,mainWindow.center.y-50,140,100)];
loadingView.opaque = NO;
loadingView.backgroundColor = [UIColor darkGrayColor];
loadingView.alpha = 0.7;
loadingView.layer.cornerRadius = 8;
loadingView.layer.masksToBounds = YES;
UIActivityIndicatorView *spinningWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[spinningWheel setCenter:CGPointMake(loadingView.frame.size.width/2,(loadingView.frame.size.height/2)-10.0f)];
[loadingView addSubview:spinningWheel];
[spinningWheel release];
[spinningWheel startAnimating];

UILabel *loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 62, 140, 25)];
[loadingLabel setFont:[UIFont boldSystemFontOfSize:14.0f]];
[loadingLabel setTextAlignment:UITextAlignmentCenter];
[loadingLabel setBackgroundColor:[UIColor clearColor]];
[loadingLabel setTextColor:[UIColor whiteColor]];
loadingLabel.text = @"Loading...";
[loadingView addSubview:loadingLabel];
[loadingLabel release];
[loadingContainerView addSubview:loadingView];
}

if (isShowActivityIndicator == false) {
[mainWindow addSubview:loadingContainerView];
isShowActivityIndicator=true;
}
}

어떤 곳에서도 [Utillity showLoadingView]를 호출하면 activity indicagtor view를 띄운다.
아래 그림은 activity indicator view를 띄운 화면을 캡쳐한 화면이다.






이와 더불어 class method에 대한 함수 포인터를 얻고 싶으면 - (IMP)methodForSelector:(SEL)aSelector 를 사용하면 된다.

댓글 없음:

댓글 쓰기