简体   繁体   English

使id符合协议,是否需要?

[英]Conform id to protocol, is it needed?

I have just been looking at some old code and it got me thinking about which of these to use, both seem to work without complaint. 我一直在看一些旧的代码,这让我开始思考使用哪个代码,两者似乎都可以正常工作。 I was just curious when I spotted the difference. 当我发现差异时,我很好奇。

THIS: 这个:

id <UIApplicationDelegate> appDelegate = [[UIApplication sharedApplication] delegate];

OR 要么

id appDelegate = [[UIApplication sharedApplication] delegate];

i guess it depends on what you are asking to appDelegate 我想这取决于您要提出的要求

i mean, if you are going use the property "window" which is defined in UIApplicationDelegate protocol: 我的意思是,如果您要使用UIApplicationDelegate协议中定义的“窗口”属性:

NSLog(@"%@",  appDelegate.window);

then you should use : 那么您应该使用:

id <UIApplicationDelegate> appDelegate = [[UIApplication sharedApplication] delegate];

but if you try: 但是,如果您尝试:

id appDelegate = [[UIApplication sharedApplication] delegate];
NSLog(@"%@",  appDelegate.window);

you'll get an error... 你会得到一个错误...

While meronix's answer is correct, it misses an important point. 尽管meronix的答案是正确的,但它遗漏了一个重点。

You should always declare variables to have the most specific type possible. 您应始终声明变量以使其具有最具体的类型。

By doing so, you give the compiler the maximum amount of information with which to validate your code. 这样,您便可以为编译器提供用于验证代码的最大信息量。 Thus, this is preferable because it tells the compiler to limit the search for selectors to a minimal number: 因此,这是可取的,因为它告诉编译器将对选择器的搜索限制为最小数目:

id <UIApplicationDelegate> appDelegate = ...;

Note that id<SomeProtocol> limits the set of valid selectors to only those that exist in SomeProtocol . 请注意, id<SomeProtocol>将有效选择器的集合限制为仅存在于SomeProtocol选择器。 This why you'll sometimes see the protocol declared as also implementing <NSObject> or you'll see id<SomeProtocol, NSObject> (or NSObject<SomeProtocol>* ) as the type declaration. 这就是为什么有时您会看到该协议声明也实现了<NSObject>或为什么将id<SomeProtocol, NSObject> (或NSObject<SomeProtocol>* )作为类型声明的原因。

Try this.. 尝试这个..

YourAppDelegate *appDelegate = (YourAppDelegate *)[[UIApplication sharedApplication]delegate];

to avoid any kind of warning 避免任何警告

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM