Your createNewGameAgainst
method is a class method (see the +
in front of the method declaration). Your checkIfGameAlreadyExistsAgainst
method is a instance method (see the -
in front of the method declaration). To call checkIfGameAlreadyExistsAgainst
from createNewGameAgainst
you need to get an instance of MESGameModel
. self
inside of createNewGameAgainst
references the class itself, not an instance of it.
Creating class extension for a Class's private methods
-
02-06-2022 - |
Pregunta
I have created a Game Model as a class. I checked out this question about creating a class extension: Best way to define private methods for a class in Objective-C
What I have is some public methods - these are open for other VCs to use in the app. I also want some private methods, that the classes public methods can make use of, but do not need to be open to the rest of the application as such.
I thought this could be accomplished by a class extension, adding an extra interface section in the implementation file but this doesn't appear to work.
Imp file:
#import "MESGameModel.h"
@interface MESGameModel ()
-(BOOL)checkIfGameAlreadyExistsAgainst:(PFUser *)opponentUser;
@end
@implementation MESGameModel
#pragma mark - Public methods
+(void)createNewGameAgainst:(PFUser *)user2 withCompletion:(void (^)(BOOL success))completionHandler{
Later on I have the declaration of the other private method:
#pragma mark - Private methods
-(BOOL)checkIfGameAlreadyExistsAgainst:(PFUser *)opponentUser {
What I am looking for is the ability to call for example [self checkIfGameAlreadyExistsAgainst...] within the public method (createNewGameAgainst).
Solución
Otros consejos
You can use the form; your problem is understanding the distinction of class methods vs instance methods.
+ (void)createNewGameAgainst:(PFUser *)user2 withCompletion:(void (^)(BOOL success))completionHandler
Is a class method (note the '+') -- you do not need an instance of MESGameModel
to call this method. However, you will have no instance of MESGameModel
within the definition (or body of) that class method. You cannot use the instance methods, properties, or ivars of the MESGameModel
because the instance of MESGameModel
is absent in a class method.
self
in this scope will be a special class which you can message but responds to the class methods.
- (BOOL)checkIfGameAlreadyExistsAgainst:(PFUser *)opponentUser;
Declares an instance method (note the '-'). An instance of MESGameModel
may respond to this message, and within that method's definition, you will have access to the instance variables, properties, instance methods, and class methods of MESGameModel
.
self
will be an instance of MESGameModel
which you can message, and responds to the instance methods.