I tried both methods i.e. using class and instance methods. Any of them will do, though to follow the proper delegation pattern I believe using instance methods is more appropriate.
Objective C delegates and class methods vs instance methods
-
07-03-2022 - |
سؤال
There is a similar question to mine on the following link but it doesn't quite answer my query.
I am setting a helper class for Facebook (follows the delegation pattern) . An example of one of the class methods would be:
+ (void)openSession:(id)delegate;
This method calls a the Facebook openActiveSessionWithReadPermissions
method which expects a completionHandler block. Would it make sense to call the delegate method, say sessionStateChanged
in the block as follows?
[delegate sessionStateChanged];
Or is it better to use instance methods for the Facebook helper class and call the delegate using [self.delegate sessionStateChanged]
in the completionHandler block.
المحلول 2
نصائح أخرى
You would be better off with a block parameter rather than a delegate as a parameter if it is just for a single callback.
+ (void)openSession:(void (^)(void))sessionStateChangedBlock
That way you don't have to worry about defining a delegate protocol.
If you want to use a delegate, you will have to define a delegate variable at the class level. You can't use [self.delegate sessionStateChanged]
because you are saving the delegate as a class variable. self
is only available in an instance of the class.