Why do unimplemented optional protocol methods cause runtime errors when that method is called in obj-c? - objective-c

I have two classes that can act as a delegate of a third class, and both implement a formal protocol made entirely of optional methods. One of the classes implements everything while another only implements a couple methods that i care about. However, at runtime when i have the second class act as the delegate to the third class, and the third class ends up calling one of the unimplemented optional methods on that delegate, i get a runtime error essentially saying "Target does not respond to this message selector." I thought that objective-c handled this case correctly, and that it would just do nothing if that method wasn't actually defined on the class. Might there be something i'm missing?

When you call an optional method of your delegate, you need to make sure it responds to the selector before calling it:
if ([delegate respondsToSelector:#selector(optionalMethod)])
[delegate optionalMethod];

Optional protocol methods simply mean the object implementing the protocol does not have to implement the method in question - the callee then absolutely must check whether the object implements the method before calling (otherwise you'll crash, as you noticed). These NSObject HOM categories can be helpful:
#implementation NSObject (Extensions)
- (id)performSelectorIfResponds:(SEL)aSelector
{
if ( [self respondsToSelector:aSelector] ) {
return [self performSelector:aSelector];
}
return NULL;
}
- (id)performSelectorIfResponds:(SEL)aSelector withObject:(id)anObject
{
if ( [self respondsToSelector:aSelector] ) {
return [self performSelector:aSelector withObject:anObject];
}
return NULL;
}
#end
Then you can simply do:
[delegate performSelectorIfResponds:#selector(optionalMethod)];

This Blocks solution works well, once you get your head wrapped around what is going on. I added a BOOL result because I wanted to be able to conditionally run one of several optional methods. Some tips if you are trying to implement this solution:
First, if you haven't encountered Extension/Categories yet, you simply add this to the top of your class, OUTSIDE the existing class definition. It will be a public or private extension based on where you put it.
#implementation NSObject (Extensions)
// add block-based execution of optional protocol messages
-(BOOL) performBlock:(void (^)(void))block ifRespondsTo:(SEL) aSelector
{
if ([self respondsToSelector:aSelector]) {
block();
return YES;
}
return NO;
}
#end
Second, here's how you call it from your code:
BOOL b = [(NSObject*)self.delegate performBlock:^{
// code to run if the protocol method is implemented
}
ifRespondsTo:#selector(Param1:Param2:ParamN:)];
Replace Param1:Param2:ParamN: with the names of each parameter for your protocol method. Each one should end with a colon.
So if your protocol method looks like:
-(void)dosomething:(id)blah withObj:(id)blah2 andWithObj(id)blah3;
the last line would look like this:
ifRespondsTo:#selector(dosomething:withObj:andWithObj:)];

Blocks might provide a better solution. They allow to conditionally perform any code based on the existence of an implementation of a given method:
-(void) performBlock:(void (^)(void))block ifRespondsTo:(SEL) aSelector{
if ([self respondsToSelector:aSelector]) {
block();
}
}
By using this addition to NSObject, you can conditionally execute any #optional method, no matter how many parameters it might have.
See How to safely send #optional protocol messages that might not be implemented

Related

Call Category's un-overridden method

I am trying to add a condition to NSObject's description method where any object that responds to a method in an optional protocol (PrettyPrinter) will print the result from the protocol method instead of the normal NSObject's description. However, if the object being printer does not respond to the protocol then the description should return how it normally does.
My current attempt at doing this involves writing a category on NSObject that contains this protocol and the overridden description method. However, I am unaware of any way to call a category's un-overridden method.
-(NSString*)description
{
if ([self respondsToSelector:#selector(prettyPrinter)]) {
return self.prettyPrinter;
}else{
// Would Like to return normal description if does not respond to selector. But
// can not call super description due to being a category instead of a subclass
return [super description];
}
}
Any ideas on ways that I can accomplish this would be greatly appreciated. Thanks!
UPDATE:
With a little more searching, it would seem like this may be able to be accomplished through something called swizzling. However, current attempts at this have not yet been successful. Any advise on techniques to use swizzling to accomplish this goal would also be helpful.
As you point out, this is possible with method swizzling. The runtime has functionality to exchange the implementation of two methods.
#import <objc/runtime.h>
#interface NSObject (PrettyPrinter)
- (NSString*) prettyPrinter;
#end
#implementation NSObject (PrettyPrinter)
// This is called when the category is being added
+ (void) load {
Method method1 = class_getInstanceMethod(self, #selector(description));
Method method2 = class_getInstanceMethod(self, #selector(swizzledDescription));
// this is what switches the two methods
method_exchangeImplementations(method1, method2);
}
// This is what will be executed in place of -description
- (NSString*) swizzledDescription {
if( [self respondsToSelector:#selector(prettyPrinter)] ) {
return [self prettyPrinter];
}
else {
return [self swizzledDescription];
// The above is not a recursive call, remember the implementation has
// been exchanged, this will really execute -description
}
}
- (NSString*) prettyPrinter {
return #"swizzled description";
}
#end
The -prettyPrinter method can be removed, in which case NSLog will return the value defined by -description.
Note that this will only swizzle -description, although NSLog might call other methods, such as NSArray's –descriptionWithLocale:
if a category overrides a method that exists in the category's class, there is no way to invoke the original implementation.
Click Here To Read More!

Overriding in subclass after checking a boolean

I plan to override a method in the subclass if a boolean is set to a certain value, and then to switch this value, and have thought of two options:
1. Calling super and checking success
// Superclass
-(BOOL) showEngine
BOOL result = !self.isEngineActive;
if (result) {
// Does something common to both super and subclass
self.isEngineActive = YES;
}
return result;
}
// Subclass override
-(BOOL) showEngine
BOOL result = [super showEngine];
if (result) {
// Does something unique to subclass
}
return result;
}
2. Delegate to a second method
// Superclass
-(void) showEngine
if (!self.isEngineActive) {
// Delegate
showEngineNow();
// Does something common to both super and subclass
self.isEngineActive = YES;
}
}
// Subclass override
-(void) showEngineNow() {
[super showEngineNow];
// Does something unique to subclass
}
The first method has the negative effect of having to call super and check the result, whereas the second has the negative baggage of a second method call to the delegate. Which would be the better way, and is there one I haven't thought of?
negative effect of having to call super
Calling the super implementation is pretty common when overriding a method. I don't see this as a negative. It's not clear from the question what you are trying to acheive, but I'd go with option 1 - why introduce more complexity?
This is assuming that the unspecified //stuff you are doing in the super implementation should also be done by the subclass. If not, you will need to split out into separate methods.
I don't think you are using "delegate" as it is intended in Cocoa. If it's just another method in the same class, it isn't a delegate. A delegate is a separate object that conforms to a known protocol.
If you feel that the methods are getting too long and doing too many things, then by all means break them up and override only the relevant parts in your subclass. In that case option 2 is your best bet, but don't call it a delegate.

ViewController may not respond to'method' problem

I know it is a common problem, I googled a lot and seems get no luck to solve my problem.
I have a #interface TestViewController:UIViewController
and in its implementation file I have a method defined:
-(void)method1 {
do something;
[self method1];//here I need to call the method itself if a statement is true and this line is where the warning TestViewController may not respond to'method1' I got
}
-(void)method2{
[self method1] //But there is no problem with this line
}
Can anyone help me?
Thanks in advance!
Your method declarations are missing in the header.
Just add
-(void)method1;
-(void)method2;
to your TestViewController.h file
Update:
The reason why you don't get a warning about the second call ([self method1] within method2) is, that the compiler already knows about method1 at that point. (because the implementation occurs before method2)
Objective-C just as C uses a single pass compiler to gather all known symbols. The result is that you can only reference methods and variables that has been declared above the current scope.
You can solve this particular problem you give an example of in three ways:
Add method1 to the public interface in the header file, just as #weichsel suggested.
If you want method1to be private then you can add it to your class by declaring an unnamed category at the top of you implementation file. Like this:
#import "Foo.h"
#interface Foo ()
-(void)method1;
#end
#implementation Foo
// ... lots of code as usual ...
#end
The third option could be regarded as hack by some, but it really a feature of the Objective-C language. Just as all methods get an implicit variable named self that is the instance the method was called on, so do all method alsa get the implicit variable named _cmd, that is of type SEL, it is the selector that was used to call this method. This can be used to quickly call the same method again:
-(void)method1 {
if (someContition) {
[self performSelector:_cmd withObject:nil];
} else {
// Do other stuff...
}
}
This is most useful if you want to make sure that a particular method is always performed on the main thread:
-(void)method {
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:_cmd withObject:nil waitUntilDone:NO];
return;
}
// Do stuff only safe on main thread
}

when to use respondsToSelector in objective-c

- (void)someMethod
{
if ( [delegate respondsToSelector:#selector(operationShouldProceed)] )
{
if ( [delegate operationShouldProceed] )
{
// do something appropriate
}
}
}
The documentation says:
The precaution is necessary only for optional methods in a formal protocol or methods of an informal protocol
What does it mean? If I use a formal protocol I can just use [delegate myMethod]?
You use it pretty much just when you think you need to: to check to see if an object implements the method you are about to call. Usually this is done when you have an optional methods or an informal protocol.
I've only ever used respondsToSelector when I'm writing code that must communicate with a delegate object.
if ([self.delegate respondsToSelector:#selector(engineDidStartRunning:)]) {
[self.delegate engineDidStartRunning:self];
}
You sometimes would want to use respondsToSelector on any method that returns and id or generic NSObject where you aren't sure what the class of the returned object is.
Just to add to what #kubi said, another time I use it is when a method was added to a pre-existing class in a newer version of the frameworks, but I still need to be backwards-compatible. For example:
if ([myObject respondsToSelector:#selector(doAwesomeNewThing)]) {
[myObject doAwesomeNewThing];
} else {
[self doOldWorkaroundHackWithObject:myObject];
}
As kubi mentioned respondsToSelector is normally used when you have a an instance of a method that conforms to a protocol.
// Extend from the NSObject protocol so it is safe to call `respondsToSelector`
#protocol MyProtocol <NSObject>
// #required by default
- (void) requiredMethod;
#optional
- (void)optionalMethod;
#end
Given and instance of this protocol we can safely call any required method.
id <MyProtocol> myObject = ...
[myObject requiredMethod];
However, optional methods may or may not be implemented, so you need to check at runtime.
if ([myObject respondsToSelector:#selector(optionalMethod)])
{
[myObject optionalMethod];
}
Doing this will prevent a crash with an unrecognised selector.
Also, the reason why you should declare protocols as an extension of NSObjects, i.e.
#protocol MyProtocol <NSObject>
Is because the NSObject protocol declares the respondsToSelector: selector. Otherwise XCode would think that it is unsafe to call it.
Old question, but I have learned to be very cautios with using stuff like addTarget:#selector(fu:) because the method name is not checked nor included in refactoring by XCODE. This has caused me quite some trouble already. So now I made it a habbit to always embed stuff like addTarget or addObserver in a respondsToSelector-Check like so:
if([self respondsToSelector:#selector(buttonClicked:)]){
[self.button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
}else{
DebugLog(#"Warning - a class or delegate did not respond to selector in class %#", self);
}
I know its not super elegant, but i'd rather add some boilerplate code than have an unexpected crash of my apps in the App Store.

Is it possible to make the -init method private in Objective-C?

I need to hide (make private) the -init method of my class in Objective-C.
How can I do that?
NS_UNAVAILABLE
- (instancetype)init NS_UNAVAILABLE;
This is a the short version of the unavailable attribute. It first appeared in macOS 10.7 and iOS 5. It is defined in NSObjCRuntime.h as #define NS_UNAVAILABLE UNAVAILABLE_ATTRIBUTE.
There is a version that disables the method only for Swift clients, not for ObjC code:
- (instancetype)init NS_SWIFT_UNAVAILABLE;
unavailable
Add the unavailable attribute to the header to generate a compiler error on any call to init.
-(instancetype) init __attribute__((unavailable("init not available")));
If you don't have a reason, just type __attribute__((unavailable)), or even __unavailable:
-(instancetype) __unavailable init;
doesNotRecognizeSelector:
Use doesNotRecognizeSelector: to raise a NSInvalidArgumentException. “The runtime system invokes this method whenever an object receives an aSelector message it can’t respond to or forward.”
- (instancetype) init {
[self release];
[super doesNotRecognizeSelector:_cmd];
return nil;
}
NSAssert
Use NSAssert to throw NSInternalInconsistencyException and show a message:
- (instancetype) init {
[self release];
NSAssert(false,#"unavailable, use initWithBlah: instead");
return nil;
}
raise:format:
Use raise:format: to throw your own exception:
- (instancetype) init {
[self release];
[NSException raise:NSGenericException
format:#"Disabled. Use +[[%# alloc] %#] instead",
NSStringFromClass([self class]),
NSStringFromSelector(#selector(initWithStateDictionary:))];
return nil;
}
[self release] is needed because the object was already allocated. When using ARC the compiler will call it for you. In any case, not something to worry when you are about to intentionally stop execution.
objc_designated_initializer
In case you intend to disable init to force the use of a designated initializer, there is an attribute for that:
-(instancetype)myOwnInit NS_DESIGNATED_INITIALIZER;
This generates a warning unless any other initializer method calls myOwnInit internally. Details will be published in Adopting Modern Objective-C after next Xcode release (I guess).
Apple has started using the following in their header files to disable the init constructor:
- (instancetype)init NS_UNAVAILABLE;
This correctly displays as a compiler error in Xcode. Specifically, this is set in several of their HealthKit header files (HKUnit is one of them).
Objective-C, like Smalltalk, has no concept of "private" versus "public" methods. Any message can be sent to any object at any time.
What you can do is throw an NSInternalInconsistencyException if your -init method is invoked:
- (id)init {
[self release];
#throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:#"-init is not a valid initializer for the class Foo"
userInfo:nil];
return nil;
}
The other alternative — which is probably far better in practice — is to make -init do something sensible for your class if at all possible.
If you're trying to do this because you're trying to "ensure" a singleton object is used, don't bother. Specifically, don't bother with the "override +allocWithZone:, -init, -retain, -release" method of creating singletons. It's virtually always unnecessary and is just adding complication for no real significant advantage.
Instead, just write your code such that your +sharedWhatever method is how you access a singleton, and document that as the way to get the singleton instance in your header. That should be all you need in the vast majority of cases.
You can declare any method to be not available using NS_UNAVAILABLE.
So you can put these lines below your #interface
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
Even better define a macro in your prefix header
#define NO_INIT \
- (instancetype)init NS_UNAVAILABLE; \
+ (instancetype)new NS_UNAVAILABLE;
and
#interface YourClass : NSObject
NO_INIT
// Your properties and messages
#end
That depends on what you mean by "make private". In Objective-C, calling a method on an object might better be described as sending a message to that object. There's nothing in the language that prohibits a client from calling any given method on an object; the best you can do is not declare the method in the header file. If a client nevertheless calls the "private" method with the right signature, it will still execute at runtime.
That said, the most common way to create a private method in Objective-C is to create a Category in the implementation file, and declare all of the "hidden" methods in there. Remember that this won't truly prevent calls to init from running, but the compiler will spit out warnings if anyone tries to do this.
MyClass.m
#interface MyClass (PrivateMethods)
- (NSString*) init;
#end
#implementation MyClass
- (NSString*) init
{
// code...
}
#end
There's a decent thread on MacRumors.com about this topic.
If you are talking about the default -init method then you can't. It's inherited from NSObject and every class will respond to it with no warnings.
You could create a new method, say -initMyClass, and put it in a private category like Matt suggests. Then define the default -init method to either raise an exception if it's called or (better) call your private -initMyClass with some default values.
One of the main reasons people seem to want to hide init is for singleton objects. If that's the case then you don't need to hide -init, just return the singleton object instead (or create it if it doesn't exist yet).
Put this in header file
- (id)init UNAVAILABLE_ATTRIBUTE;
well the problem why you can't make it "private/invisible" is cause the init method gets send to id (as alloc returns an id) not to YourClass
Note that from the point of the compiler (checker) an id could potencialy respond to anything ever typed (it can't check what really goes into the id at runtime), so you could hide init only when nothing nowhere would (publicly = in header) use a method init, than the compile would know, that there is no way for id to respond to init, since there is no init anywhere (in your source, all libs etc...)
so you cannot forbid the user to pass init and get smashed by the compiler... but what you can do, is to prevent the user from getting a real instance by calling a init
simply by implementing init, which returns nil and have an (private / invisible) initializer which name somebody else won't get (like initOnce, initWithSpecial ...)
static SomeClass * SInstance = nil;
- (id)init
{
// possibly throw smth. here
return nil;
}
- (id)initOnce
{
self = [super init];
if (self) {
return self;
}
return nil;
}
+ (SomeClass *) shared
{
if (nil == SInstance) {
SInstance = [[SomeClass alloc] initOnce];
}
return SInstance;
}
Note : that somebody could do this
SomeClass * c = [[SomeClass alloc] initOnce];
and it would in fact return a new instance, but if the initOnce would nowhere in our project be publicly (in header) declared, it would generate a warning (id might not respond ...) and anyway the person using this, would need to know exactly that the real initializer is the initOnce
we could prevent this even further, but there is no need
I have to mention that placing assertions and raising exceptions to hide methods in the subclass has a nasty trap for the well-intended.
I would recommend using __unavailable as Jano explained for his first example.
Methods can be overridden in subclasses. This means that if a method in the superclass uses a method that just raises an exception in the subclass, it probably won't work as intended. In other words, you've just broken what used to work. This is true with initialization methods as well. Here is an example of such rather common implementation:
- (SuperClass *)initWithParameters:(Type1 *)arg1 optional:(Type2 *)arg2
{
...bla bla...
return self;
}
- (SuperClass *)initWithLessParameters:(Type1 *)arg1
{
self = [self initWithParameters:arg1 optional:DEFAULT_ARG2];
return self;
}
Imagine what happens to -initWithLessParameters, if I do this in the subclass:
- (SubClass *)initWithParameters:(Type1 *)arg1 optional:(Type2 *)arg2
{
[self release];
[super doesNotRecognizeSelector:_cmd];
return nil;
}
This implies that you should tend to use private (hidden) methods, especially in initialization methods, unless you plan to have the methods overridden. But, this is another topic, since you don't always have full control in the implementation of the superclass. (This makes me question the use of __attribute((objc_designated_initializer)) as bad practice, although I haven't used it in depth.)
It also implies that you can use assertions and exceptions in methods that must be overridden in subclasses. (The "abstract" methods as in Creating an abstract class in Objective-C )
And, don't forget about the +new class method.