在objective-c中我有一個奇怪的問題。下面是代碼:在Objective-c問題中訪問委託靜態方法問題
STViewController.h
#import <UIKit/UIKit.h>
@interface STViewController : UIViewController <UIAlertViewDelegate>
+(void)myStaticMethod;
@end
STViewController.m
#import "STViewController.h"
@implementation STViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[STViewController myStaticMethod];
}
+ (void)myStaticMethod {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Foo bar"
message:@"baz bat"
//what does self even mean in this context? The class object STViewController?
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
[alert show];
[alert release];
}
#pragma mark UIAlertViewDelegate
// TRICKY PART if it's static it works, if it's not, it doesn't.
// even though the protocol declares instance methods (with a minus).
+ (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSLog(@"It works!");
}
@end
爲什麼會出現這種情況?它是否正確?我沒有收到任何錯誤或警告。協議方法聲明中的 -/+是否執行某些操作?
類方法的範圍中沒有自我。你可以引用一個單例。 – 2013-02-26 09:21:55
@NickWeaver你可以在類方法中使用'self',它將指向'Class'對象爲'[MyClass class]' – 2013-02-26 09:38:32
@xlc我的不好,謝謝澄清。 – 2013-02-26 10:46:34