在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