Variables in both the interface and as a property using Objective-C
What is the difference between
@interface URLCacheConnection : NSObject {
id <URLCacheConnectionDelegate> delegat开发者_StackOverflow中文版e;
}
@property (nonatomic, assign) id delegate;
@end
and
@interface URLCacheConnection : NSObject {
}
@property (nonatomic, assign) id<URLCacheConnectionDelegate> delegate;
@end
These two class definitions both seem to behave the same. What is the purpose of defining variables in both the interface and as a property?
What is the difference between...
The main difference is that in the first case you'll be able to see the delegate
ivar in the debugger, while in the second you won't.
What is the purpose of defining variables in both the interface and as a property?
It's partly a matter of backward compatibility. The ability to synthesize instance variables is a relatively new feature of Objective-C. Furthermore, it'll probably always be desireable to be able to create instance variables for internal use and that have no corresponding property.
First, the two are not quite identical. For the first, the compiler will allow you to assign any object as the delegate, while for the second it will complain if the object you assign doesn't conform to the URLCacheConnectionDelegate protocol. That's easily enough fixed, of course.
In earlier versions of Apple's Objective-C compiler, it was required to explicitly declare the ivar backing a property in order to use @synthesize. At some point (I forget exactly when) they changed it to allow the compiler/runtime to automatically create the needed ivar.
The difference will be in the implementations. With the first you can @synthesize the getters and setters and will have access to the declared internal variable.
With the second you will have to use @dynamic and code the getters and setters because there is no internal variable which XCode can generate code for.
That's my reading - happy to know if it's wrong.
<Later> Yep - wrong :-(
精彩评论