Referencing an object that doesn't exist yet
Question
I have a working piece of code in the application delegate that contains a reference to a view that may or may not be created during the course of the use of the app. This code will only be eventually called after the referenced object comes into existence, so there is not possibility of a crash.
However, the compiler detects this reference and give a warning:
warning: Semantic Issue: Instance method
'-dismissPurchasingViewAndUpdateSetupView' not found (return type
defaults to 'id')
In a nutshell, this is what is happening:
In application delegate:
@interface appDelegate : NSObject
{
NSObject *purchasingView;
}
@property (nonatomic, retain) NSObject *purchasingView;
@end
@implementation appDelegate
@synthesize purchasingView;
-(void)aMethod
{
[purchasingView dismissPurchasingViewAndUpdateSetupView];
}
In a view controller:
-(void) someOtherMethod
{
//Let the app delegate know about the reference to this view
appDelegate *appDelegate = (appDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.purchasingView = self;
}
-(void)dismissPurchasingViewAndUpdateSetupView
{
[self dismissModalViewControllerAnimated:YES];
}
The app delegate implements a SKPaymentTransactionObserver
and it receives App Store notifications triggered by purchases in the view controller. When a purchase completes the app delegate notifies the view controller to dismiss it self.
Is this a sensible way to do this? Is there a way to get the compiler to ignore the fact that when the app runs for the first time, the purchasingView
pointer is pointing to null?
Solution
You're not getting the error because purchasingView
may be nil
when the application starts.
You're getting the error because purchasingView
is an NSObject
, and NSObject
doesn't implement the -dismissPurchasingViewAndUpdateSetupView
method. If you change the type of purchasingView
to whatever class it is where you implemented purchasingView
, then the error will go away.
OTHER TIPS
The compiler is not detecting anything about purchasingView
being nil
at first run. It doesn't do that. The compiler is not concerned with what the value of your variables are at runtime. Also, it's perfectly valid to message nil
anyway and is quite a well used "feature" of the Objective-C runtime.
Your problem is that in the application delegate you're presumably not #import
-ing the header for whatever class your purchasingView
is, and you're saying that purchasingView
is an NSObject
in appDelegate
. Change that to be the actual class of purchasingView
and #import
the header in your application delegate header.
[purchasingView perfromSelector:@selector(dismissPurchasingViewAndUpdateSetupView)]