How to call a method through the object created by interface in Objective-C - objective-c

I need to call a method through the object created by the interface ie
id<MyProtocol>obj;
Now i have created this obj in my main class where i am not implementing the methods of this protocol but i need to access the method which is already implemented in someother class.I am now calling the method as follows
[obj load];
in my main class in the applicationDidFinishLaunching, but i not able to access the method?
Pls do suggest me the correct way of calling the methods through protocols...

A protocol implements nothing. It only describes a set of messages that the object should respond to. Your obj object belongs to some class. This class needs to implement methods described in MyProtocol.
Edit
A protocol is not implemented by a specific class. Any class that claims to conform to a protocol must implement its methods. Any object that claims to conform to a protocol must belong to a class that implements its methods.
In your case, obj is a ClassB, so ClassB must implement methods described by MyProtocol, either directly or through inheritance.

[obj load] is OK. If you want to shut up the compiler you can cast it to id:
[(id)obj load];
But if you know you'll need to call the -load method, maybe you should add the -load method to the protocol, or make another protocol that has the -load method e.g.
#protocol Loadable
-(void)load;
#end
...
id<MyProtocol, Loadable> obj;

Related

Why can't I use the classname instead of self in objective c

It's just something which is not logical for me. Sure it's useful to call methods within in a class by the self-keyword. But why isn't it possible calling it by the own classname??
e.g.
[MyClassWhereIAmActuallyIn anyRandomMethod]; instead of [self anyRandomMethod];
Because that has a different meaning.
[self someMethod]
sends someMethod to the object, whose reference is stored in the (slightly magic) variable self.
[SomeClass someMethod]
sends someMethod to the class object (yes, classes are objects, too), which contains the meta-information for class SomeClass.
Two different objects ("receivers"). Also note, that there are class methods in Objective-C (i.e., you can take advantage of the fact, that classes are objects, and define new methods for them). Observe:
#interface SomeClass
- (void) someMethod;
+ (void) someMethod;
#end
These are completely different methods, intended for completely different receivers. The method tagged with - is an instance method (will be used, e.g., with self). The method tagged with + is a class method (and will be used with the class object).
You can call class method ('+') like that. Self is a pointer to an instance of your class in instance methods ('-'), self points to the singleton Class-object when you are in class methods ('+').
In OOP this is the difference between the class object and an instance of that class object. When you create a method, you specify whether it is a class method (+) or an instance method (-). Once the method is defined you need to call it in the appropriate way (on the class object or on an instance of that class).

Create an instance from a Class that conforms to a Protocol

I'm trying to accomplish something like the following:
- (id<SomeProtocol>)instanceFromClass:(Class<SomeProtocol>)cls
{
return [[cls alloc] initUsingSomeConstructorDefinedInProtocolWithValue:_value];
}
However, I'm getting a No Known class method for selector 'alloc' error. How may I specify in my signature that I want to receive a class that conforms to a protocol? Or, if that part is correct, how may I create an instance from that argument using a constructor defined in the specified protocol?
Not sure why the compiler complains but you can fix by casting your parameter back to Class
- (id<SomeProtocol>)instanceFromClass:(Class<SomeProtocol>)cls
{
return [[(Class)cls alloc] initUsingSomeConstructorDefinedInProtocolWithValue:_value];
}
while still getting you the type checking you want for the parameter as hinted at in this SO answer: Declare an ObjC parameter that's a Class conforming to a protocol
Your use of the protocol is 'fine'. The issue is that the cls parameter is tagged as a class which conforms to a protocol that defines instance methods (the init method). This doesn't tell the compiler that the +alloc method is available because that is a class method on NSObject.
You can add the +alloc method to the protocol. Or you can do some casting to tell the compiler to trust you.
+ alloc is a method defined by the top level class NSObject. When you have a class like Class <SomeProtocol>, the compiler only knows that this is some class and it implements SomeProtocol but it cannot know if that is a subclass of NSObject or not, since in Obj-C you can define own top-level classes that don't inherit from NSObject (not that this is generally a good idea but it is possible).
There is a special "hack" in the compiler that in case the type is just Class, the compiler will always assume that it is a subclass of NSObject and would only fail at runtime in case it isn't. But this hack only works for the exact type Class and not for Class <SomeProtocol> which is a distinct type.
So what you can do is to either cast to Class, so the hack works again:
[[(Class)cls alloc] ...]
or you can also do that
[[cls.class alloc] ...]
in case that cls will be a subclass of NSObject at runtime because then it will have a + class method.
Note that if I call instanceFromClass: with a class, that does implement SomeProtocol but is no subclass of NSObject and also does not implement a + alloc method, both methods above will fail at runtime and the app will crash.

-forwardInvocation for class methods

I'm struggling to forward a class method through a facade class.
To clarify, I'm overriding all the following methods:
-(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
-(void)forwardInvocation:(NSInvocation *)anInvocation
+(BOOL)instancesRespondToSelector:(SEL)aSelector
+(NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector
+(IMP)instanceMethodForSelector:(SEL)aSelector
+(BOOL)resolveClassMethod:(SEL)sel
+(BOOL)resolveInstanceMethod:(SEL)sel
.. and yet, for the class method, the only one to be called is +resolveClassMethod. From there, I immediately get an unrecognized selector exception regardless of whether I return YES or NO.
What's going on?
Does class message forwarding work differently to instance message forwarding?
Similarly, why isn't there a +forwardInvocation class method?
Any help would be greatly appreciated.
So you already know that to make an object do forwardInvocation for instance methods, you have to implement the instance methods -forwardInvocation: and -methodSignatureForSelector: (the others are unnecessary). Well, class methods are just methods on the class object. Classes are objects and work like any other objects, and support all the instance methods of the root class (NSObject in this case).
The Objective-C runtime doesn't care that an object is a class object or non-class object. The message forwarding mechanism is the same. So when you send a message to an object, whatever it is, and it can't find it, it just looks for the forwardInvocation: and methodSignatureForSelector: methods on the object. So you need to have these methods on your class object.
i.e. implement the class methods +forwardInvocation: and +methodSignatureForSelector:

Can an ObjC class object conform to a protocol?

Is there a way to indicate to the compiler that a class object conforms to a protocol?
As I understand, by creating +(void)foo class methods, an instance of that class object will have those methods as instance methods. So, as long as I create +(void)foo methods for all required protocol methods, I can have a class object act as a delegate.
My problem of course is that in the class's header file, I only know how to indicate that instances of the class conform to the protocol (as is typically the case). So, the best I've figured out is to cast the class object like so:
something.delegate = (id<SomethingDelegate>)[self class]
Any ideas?
Related, but different:
ObjC: is there such a thing as a "class protocol"?
What you're doing now is correct as it will silence warnings which is your goal. You will be sending the class object messages defined in the protocol for instances which is a bit confusing, but the runtime doesn't care.
Think about it this way: you want to set a delegate to an object that responds to the messages defined in the protocol. Your class does this, and your class is also an object. Therefore, you should treat your class like an object that conforms to that protocol. Therefore, what you've written is completely correct (based on what you're trying to do).
One thing to note, though, is this class will not properly respond to conformsToProtocol:. This is generally okay for a delegate setup anyway (delegates don't usually check if the class conforms — they just check if it can respond to a selector).
As a side note, one thing you can do syntactically is:
Class<SomethingDelegate> variable = (Class<SomethingDelegate>)[self class];
The difference here is that the compiler will use the class methods from the protocol instead of instance messages. This is not what you want in your case, though.
There is no Objective-C syntax to indicate that a metaclass conforms to a protocol.
I think you can do it at runtime, by using class_addProtocol on the metaclass. But I haven't tried it.
I guess you could also write a +conformsToProtocol: method on your class, and lie about your conformance. This could have unexpected side-effects, since there's already a +conformsToProtocol: on NSObject (in addition to -conformsToProtocol:).
Neither of these will eliminate the need for a cast to shut the compiler up. Just use a singleton.

Introspect parameter of type: id to decide whether it is a class or a protocol

I have the following method:
-(void)SomeMethod:(id)classOrProtocol;
It will be called like this:
[self someMethod:#protocol(SomeProtocol)];
Or
[self someMethod:[SomeClass class]];
Within the method body I need to decide if |classOrProtocol| is:
Any Class(Class) OR Any Protocol(Protocol) OR Anything else
[[classOrProtocol class] isKindOfClass: [Protocol class]]
Results in a (build)error:
Receiver 'Protocol' is a forward class and corresponding #interface may not exist
So how can I tell a Protocol from a Class from anything else?
In Objective-C 2 (i.e. unless you use 32 bit runtime on OS X) Protocol is defined to be just a forward class, see /usr/include/objc/runtime.h. The real interface is nowhere declared. You can try to include /usr/inlcude/objc/Protocol.h by saying
#import <objc/Protocol.h>
but as is written there, no method is publicly supported for an instance of Protocol. The only accepted way to deal with Protocol instances is to use runtime functions, given in Objective-C Runtime Reference. It's not even publicly defined whether Protocol is a subclass of anything, and it's not even stated that it implements NSObject protocol. So you can't call any method on it.
Of course you can use the source code of the runtime to see what's going on. Protocol inherits from Object (which is a remnant from pre-OpenStep NeXTSTep), not from NSObject. So you can't use the familiar methods for NSObject-derived objects, including Class of NSObject-derived objects. See the opensourced implementations of Protocol.h and Protocol.m. As you see there, the class Protocol itself doesn't do anything, because every method just casts self to protocol_t and calls a function. In fact, as can be seen from the function _read_images and others in objc-runtime-new.mm, the isa pointer of a Protocol object is set by hand when the executable and libraries are loaded, and never used.
So, don't try to inspect whether an id is a Protocol or not.
If you really need to do this, you can use
id foo=...;
if(foo->isa==class_getClass("Protocol")){
...
}
But, seriously, don't do it.
This is not an issue 'caused by inability to determine whether it's class or protocol. The error is 'caused by missing interface of Protocol class. Make sure you import Protocol.m at the top of your implementation file where you're testing argument's type.
You can also try using NSClassFromString() function which will return Class object or nil. Do note though that if nil is returned it doesn't mean that argument is protocol. It just means that it could be undefined class too!
There is also method NSProtocolFromString which returns appropriate results - Protocol for protocol and nil for undefined protocol.