我在 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
为什么会发生这种情况?它是否正确?我没有收到任何错误或警告。协议方法声明中的 -/+ 是否有作用?
在类方法中self
指的是类对象。类对象是一个普通的 objc 对象(派生自NSObject
)将接收发送到类(类方法,带有“+”的方法)的消息。
在您的例子中,您使用类对象作为UIAlertView
(之所以有效,是因为 UIAlertView 的 API 没有明确要求静态类型的对象id<UIAlertViewDelegate>
)。现在,警报视图只会将其委托消息发送到类对象,这也很好,因为您将它们实现为类方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)