This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Conforming protocol privately
A class of mine tries to register itself as the delegate to a NSXMLParser object that it creates. However, I don't think I want my class to publicly disclose that it implements the NSXMLParserDelegate protocol, since that NSXMLParser object is a private variable used only from within the class.
Am I right to avoid disclosing the protocol, and if so, how do I implement the protocol without making it public that the class does so?
Try putting this in your .m file:
#interface MyClass (Private) <NSXMLParser>
#end
The specific category name (Private) doesn't matter – in fact you can use an empty set of parentheses (see below) – but I think this should require you to implement the required methods and tell the compiler that your class implements the protocol, at least in that file.
If that doesn't work, try simply removing <NSXMLParser> from your .h file, and casting self to id<NSXMLParser> if necessary, when setting the parser's delegate.
Related
Trying to understand protocols and their use... having a hard time of it. The more I read, the less I am able to even formulate questions about them. I've read the statement "a protocol is a contract" a hundred times, but it just doesn't click.
I "only" want to develop really simple apps, so assume that I would not myself create a protocol for any of my classes.
I do want to use Apple's Scenekit framework, for example, and understand that I am required to implement some methods to do this - for example the SCNSceneRendererDelegate. The compiler enforces this, and it knows to do that because in my header file I have inserted:
#interface AAPLGameViewController : UIViewController <SCNSceneRendererDelegate>
the bit between the angle brackets specifically.
For the prototypes of the functions I have to implement, I go look for a
#protocol
...
#end
section in the SCNSceneRendererDelegate header file.
But now I've come across some #protocol sections (e.g. in the UIApplication header file) that contain #properties!! I thought #protocol was only about implementing certain methods, what is a property doing there?
I also came across in one of the answers here that specifying a protocol name when creating an instance of an object allows me to use objects that I know nothing about. I would be very grateful to get a few simple practical examples of where this would be useful.
And finally, in Java, the counterpart to (Obj-C) #protocols are called interfaces. Is there a counterpart in Java to (Obj-C) #interface?
Thanks much, cheers.
Adhering to a protocol tells other classes that your class has a specific set of characteristics. Usually protocols are used to define what methods a specific class should have so that it can be the delegate of another class, meaning the class adopting the protocol is guaranteed to have defined the required methods that the delegate class will call in a callback. If the protocol defines a property, it simply means any classes adopting the protocol are expected to also have that property. For example:
#protocol MyProtocol <NSObject>
#required
#property (readonly) NSString *title;
#optional
- (void) someMethod;
#end
I can now define a method anywhere that takes an object conforming to MyProtocol and safely access the title property because it is guaranteed to exist for all classes adopting MyProtocol.
-(void)printTitleOfObject:(id<MyProtocol>)object {
NSLog(#"%#", object.title);
}
So even though id can be any object, since we know that it conforms to our protocol we know that it has the title property. When people say "a protocol is a contract", what they mean is even if we don't know specifically what class is adopting the protocol, we know it at least has the methods and properties listed as required in the protocol. Specifying a protocol for a class allows us to know some information about it, even if we don't know what class it is.
Apple has written documentation for protocols they've written, like the SCNSceneRendererDelegate you mentioned in your question.
But now I've come across some #protocol sections (e.g. in the
UIApplication header file) that contain #properties!! I thought
#protocol was only about implementing certain methods, what is a
property doing there?
Properties are methods. A property declaration is simply a declaration for a getter-setter method pair (or if a readonly property, just a getter method), and allows the compiler to turn a dot notation access into a call to this getter and setter. That's all a property is. How the getter/setter is implemented (whether manually implemented or synthesized), and whether it reflects an underlying value or not (or is computed from other things) are private implementation details of the getter/setter methods.
This question already has answers here:
Defining an Objective-C Class without a base Class - Compiler Warning
(3 answers)
Closed 8 years ago.
Is it possible to create a class in Objective-C without a superclass.
If I create something like
#interface Samp
#end
I get the error message: "Class Samp defined without specifying a base class".
How come NSProxy compiles?
The pedantic answer is yes, you can. You just have to make your class a root class, which you can do by using the compiler attribute objc_root_class.
__attribute__((objc_root_class))
#interface Samp
#end
or using the convenience macro NS_ROOT_CLASS
NS_ROOT_CLASS
#interface Samp
#end
This is the same thing NSProxy does.
NS_ROOT_CLASS
#interface NSProxy <NSObject> {
Class isa;
}
Now, unless you're doing something really specific and out of the schemes, I don't see why you would want to do that.
Juts make your class to inherit from an existing root class, like NSObject (the most common) or NSProxy.
How come NSProxy compiles?
NSProxy class is special - it is one of Cocoa's two public root classes (NSObject is the other one). If you must define your own root class, this answer tells you how to do it. However, in practice there should be no reason to implement your own root class.
This question already has answers here:
Must every ivar be a property?
(4 answers)
Is the use of instance variables discouraged? [duplicate]
(1 answer)
Closed 9 years ago.
I am refactoring old code and wonder - with the advent of auto-synthesized properties and class extension, should most instance variables declarations be done in the form of properties as best practice?
Yes, best practice is to use properties, either in the interface file or implementation file class extension based on wether the property is by design public or private to the class.
It would depend on your coding style. Generally, put ivars that you want accessible to other classes as properties in the .h-file.
If you declare properties but leave #synthesize to the compiler, they will automatically be synthesized so that the property myInstanceVariable is internally called _myInstanceVariable.
Accessing _myInstanceVariable directly means that you will bypass any setters/getters which is sometimes desired internally in classes, especially when the getter creates an object.
However, often when I have internal simple ivars which don't require any setter/getter, I use the ivars directly in the class extension:
// MyClass.m
#import MyClass.h
#interface MyClass() {
BOOL _simpleInternalVariable;
NSUInteger _anotherSimpleInternalVariable;
}
#end
#implementation MyClass
- (void)someMethod
{
_simpleInternalVariable = YES;
_anotherSimpleInternalVariable = 4;
}
#end
This yields exactly the same result as #property BOOL simpleInternalVariable; except that you are sure that no setter/getter is automatically created by the compiler. I sometimes prefer this way because you can't write self.simpleInternalVariable. Writing self.ivar means a getter runs somewhere but you don't always know if it's a custom getter or synthesized getter. When writing _ivar, I always know that I'm dealing with the ivar directly.
For objects though, I always use properties both in the .h- and .m-files. I could theoretically do the same thing I did above with objects, but it's just a reflex from the non-ARC days where you always wanted the compiler to generate setters which retained/released objects.
I've been looking at Apple's MVCNetworking example project and part of the interface definition for AppDelegate is puzzling me. In the .h file we have this:
#interface AppDelegate : NSObject
{
...
But in the .m file we have this:
#interface AppDelegate () <SetupViewControllerDelegate>
...
So this class is privately conforming to the protocol. But why would you want to do this instead of publicly declaring it in the header?
In general, you should publicly expose as little as possible. The fact that the AppDelegate can be a SetupViewController's delegate is probably used when the AppDelegate presents a SetupViewController. No other class should be setting the AppDelegate as some other SetupViewController's delegate, so it wouldn't make sense to publicly advertise that conformance.
It looks like the implementation uses a SetupViewController internally in one of its "private" methods presentSetupViewControllerAnimated:. Since the view controller is not publicly accessible (through a property or otherwise), there's no need to declare the class as conforming to the protocol from the public point of view. In other words, the protocol is related only to the implementation of the class, and not to the public interface that it presents.
There are times where you want to be a delegate for another object, but in so doing you may get compiler warnings because you aren't explicitly declaring that your class conforms to the required methods of the protocol. As others have mentioned, one of the pillars of Object Oriented programming is information hiding. It is not desirable to declare in your header that a class implements a particular protocol because you would be breaking that principle. It also opens your class to abuse or to be used in ways it was not intended because it is making that information known to other classes. By declaring a private category in the .m file and letting the compiler know of your intention to implement this protocol, you not only get rid of the warnings that may crop up, but you are, in effect, making your code self-documenting.
Maybe because you don't want anybody to know about your protocol with except yourself. So no somebody externally of AppDelegate will pass instance of Appdelegate as delegate to another class instance. So you will able to pass it as this internally.
In Objective-C, I can add methods to existing classes with a category, e.g.
#interface NSString (MyCategory)
- (BOOL) startsWith: (NSString*) prefix;
#end
Is it also possible to do this with protocols, i.e. if there was a NSString protocol, something like:
#interface <NSString> (MyCategory)
- (BOOL) startsWith: (NSString*) prefix;
#end
I want to do this since I have several extensions to NSObject (the class), using only public NSObject methods, and I want those extensions also to work with objects implementing the protocol .
To give a further example, what if I want to write a method logDescription that prints an object's description to the log:
- (void) logDescription {
NSLog(#"%#", [self description]);
}
I can of course add this method to NSObject, but there are other classes that do not inherit from NSObject, where I'd also like to have this method, e.g. NSProxy. Since the method only uses public members of protocol , it would be best to add it to the protocol.
Edit: Java 8 now has this with "virtual extension methods" in interfaces: http://cr.openjdk.java.net/~briangoetz/lambda/Defender%20Methods%20v4.pdf. This is exactly what I would like to do in Objective-C. I did not see this question earning this much attention...
Regards,
Jochen
Short answer: No.
Long answer: how would this work? Imagine you could add methods to existing protocols? How would this work? Imagine we wanted to add another method to NSCoding, say -(NSArray *) codingKeys; This method is a required method that returns an array of the keys used to encoding the object.
The problem is that there are existing classes (like, say NSString) that already implement NSCoding, but don't implement our codingKeys method. What should happen? How would the pre-compiled framework know what to do when this required message gets sent to a class that does not implement it?
You could say "we can add the definition of this method via a category" or "we could say that any methods added via these protocol categories are explicitly optional". Yes, you could do this and theoretically get around the problem I've described above. But if you're going to do that, you might as well just make it a category in the first place, and then check to make sure the class respondsToSelector: before invoking the method.
While it's true that you can't define categories for protocols (and wouldn't want to, because you don't know anything about the existing object), you can define categories in such a way that the code only applies to an object of the given type that has the desired protocol (sort of like C++'s partial template specialization).
The main use for something like this is when you wish to define a category that depends on a customized version of a class. (Imagine that I have UIViewController subclasses that conform to the Foo protocol, meaning they have the foo property, my category code may have need of the foo property, but I can't apply it to the Foo protocol, and if I simply apply it to UIViewController, the code won't compile by default, and forcing it to compile means someone doing introspection, or just screwing up, might call your code which depends on the protocol. A hybrid approach could work like this:
#protocol Foo
- (void)fooMethod
#property (retain) NSString *foo;
#end
#implementation UIViewController (FooCategory)
- (void)fooMethod {
if (![self conformsToProtocol:#protocol(Foo)]) {
return;
}
UIViewController<Foo> *me = (UIViewController<Foo>*) self;
// For the rest of the method, use "me" instead of "self"
NSLog(#"My foo property is \"%#\"", me.foo);
}
#end
With the hybrid approach, you can write the code only once (per class that is supposed to implement the protocol) and be sure that it won't affect instances of the class that don't conform to the protocol.
The downside is that property synthesis/definition still has to happen in the individual subclasses.
extObjC has the NEATEST stuff you can do with Protocols / Categories... first off is #concreteprotocol...
Defines a "concrete protocol," which can provide default implementations of methods within protocol.
An #protocol block should exist in a header file, and a corresponding #concreteprotocol block in an implementation file.
Any object that declares itself to conform to this protocol will receive its method implementations, but only if no method by the same name already exists.
MyProtocol.h
#protocol MyProtocol
#required - (void)someRequiredMethod;
#optional - (void)someOptionalMethod;
#concrete - (BOOL)isConcrete;
MyProtocol.m
#concreteprotocol(MyProtocol) - (BOOL)isConcrete { return YES; } ...
so declaring an object MyDumbObject : NSObject <MyProtocol> will automatically return YES to isConcrete.
Also, they have pcategoryinterface(PROTOCOL,CATEGORY) which "defines the interface for a category named CATEGORY on a protocol PROTOCOL". Protocol categories contain methods that are automatically applied to any class that declares itself to conform to PROTOCOL." There is an accompanying macro you also have to use in your implementation file. See the docs.
Last, but NOT least / not directly related to #protocols is
synthesizeAssociation(CLASS, PROPERTY), which "synthesizes a property for a class using associated objects. This is primarily useful for adding properties to a class within a category. PROPERTY must have been declared with #property in the interface of the specified class (or a category upon it), and must be of object type."
So many of the tools in this library open (way-up) the things you can do with ObjC... from multiple inheritance... to well, your imagination is the limit.
It isn't really meaningful to do so since a protocol can't actually implement the method. A protocol is a way of declaring that you support some methods. Adding a method to this list outside the protocol means that all "conforming" classes accidentally declare the new method even though they don't implement it. If some class implemented the NSObject protocol but did not descend from NSObject, and then you added a method to the protocol, that would break the class's conformance.
You can, however, create a new protocol that includes the old one with a declaration like #protocol SpecialObject <NSObject>.
I think you may be mixing up terms here and there. Extensions, Categories, Protocols, Interfaces and Classes are all different things in Objective-C. In The Objective-C 2.0 Language Apple describes the differences very well, including the benefits and drawbacks to using categories and extensions.
If you think about it, what is a "Category" or "Extension" in the conceptual sense? It's a way of adding functionality to a Class. In Objective-C, protocols are designed to have no implementation. Therefore, how would you add or extend the implementation of something that doesn't have implementation to begin with?
if you're already writing a category, why not just add in the protocol definition in the header right after the category definition?
i.e.
#interface NSString (MyCategory)
- (BOOL) startsWith: (NSString*) prefix;
#end
#protocol MyExtendedProtocolName <NSString>
//Method declarations go here
#end
this way any class that imports the category header will also get the protocol definition, and you can add it into your class..
#interface MyClass <OriginalProtocol,MyExtendedProtocolName>
also, be careful when subclassing NSString, it's a cluster and you may not always get the behaviour you're expecting.
Adam Sharp posted a solution that worked for me.
It involves 3 steps:
Defining the methods you want to add as #optional on a protocol.
Making the objects you want to extend conform to that protocol.
Copying those methods into those objects at runtime.
Check out the link for the full details.