ViewController may not respond to'method' problem - objective-c

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
}

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!

Undeclared method in Objective-C

#import "PsychologistViewController.h"
#import "HappinessViewController.h"
#interface PsychologistViewController()
#property (nonatomic) int diagnosis;
#end
#implementation PsychologistViewController
#synthesize diagnosis = _diagnosis;
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"ShowDiagnosis"]) {
[segue.destinationViewController setHappiness:self.diagnosis];
}
else if ([segue.identifier isEqualToString:#"Celebrity"]) {
[segue.destinationViewController setHappiness:100];
}
else if ([segue.identifier isEqualToString:#"Serious"]) {
[segue.destinationViewController setHappiness:20];
}
else if ([segue.identifier isEqualToString:#"TV Kook"]) {
[segue.destinationViewController setHappiness:50];
}
}
****- (void)setAndShowDiagnosis:(int)diagnosis****
{
self.diagnosis = diagnosis;
[self performSegueWithIdentifier:#"ShowDiagnosis" sender:self];
}
-(IBAction)flying
{
[self setAndShowDiagnosis:85];
}
-(IBAction)apple
{
[self setAndShowDiagnosis:100];
}
-(IBAction)dragons
{
[self setAndShowDiagnosis:20];
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#end
My question pertains to the - (void)setAndShowDiagnosis:(int)diagnosis method. This method is undeclared anywhere as either public in any .h file and obviously it's not there privately either. My question is why the reason for this would be? It just shows its setter implementation but the actual method declaration appears nowhere. Any help to clarify this is appreciated. Oh and this is from an online lecture and everything compiles just fine and runs.
Methods do not need to be declared, publicly, privately, or otherwise. Declaring a method in a .h file gives other users of the class knowledge of those methods. By not declaring it, you are hiding that method from the rest of the program that is using the class.
This method is undeclared anywhere as either public in any .h file and
obviously it's not there privately either.
I think you answered your own question, its coming up undeclared, because it isn't being declared. Unless I am reading this wrong?
You don't have to declare methods if you want them to private. There is no such thing as private methods in objective-c.
The difference between declaring a method in the header file, and a class extension at the top of implmentation file, is that if you don't declare it in the header, and you use the method from another class then the compiler will warn you that the method may not exist. But as long as you've implemented the method the application will not crash and the method will be called.
You could get away with not declaring any methods anywhere, but you will get lots of compiler warnings and it is harder to read later on, and harder for other people to understand your code. And there will be greater chance of you causing a crash because you miss spelt a method name,or some other trivial mistake.

How do I get rid of the warning <Class> may not respond to <Selector>?

The below code behaves as expected however the compiler keeps telling me this:
warning: 'StatusViewController' may not respond to '-beginLoadingThreadData'
How do I get rid of that warning and most important why xcode believes that is the case?
here is my code:
[self beginLoadingThreadData]; // called in the loadDidView block
- (void)beginLoadingThreadData
{
[NSThread detachNewThreadSelector:#selector(loadThreadData) toTarget:self withObject:nil];
}
- (void)loadThreadData
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSThread sleepForTimeInterval:2];
[self performSelectorOnMainThread:#selector(finishedLoadingThreadData) withObject:nil waitUntilDone:NO];
[pool release];
}
- (void)finishedLoadingThreadData
{
[[BusinessLogic instance] startTracking:self];
}
Declare that method before you use it. I'm assuming it's a private method, in which case you would add a class extension at the top of the implementation file:
#interface MyClass ()
- (void) beginLoadingThreadData;
#end
If it's a public method, make sure you've declared the method in your header and #imported the header at the top of the implementation file.
You have to either move the definition of loadingThreadData before the definition of viewDidLoad, or define it in the header file for StatusViewController, for example by inserting -(void)beginLoadingThreadData; before the #end in the header file (probably StatusViewController.h).
The reason is that if you don't do this, when the compiler reached your viewDidLoad method, and sees the call to beginLoadingThreadData, it has not yet seen the definition of beginLoadingThreadData, and hasn't been assured (by seeing a declaration with the method signature in the header file) that such a definition exists. Therefore it warns you that the method you're trying to call might not exist.

Why do unimplemented optional protocol methods cause runtime errors when that method is called in obj-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

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.