Reputation: 21
I have an object called Shot
which is a subclass of UIIMageView
.
// Shot.h
#import <Foundation/Foundation.h>
@interface Shot : UIImageView {
CGPoint position;
}
- (void)SetShot:(CGPoint *)point;
@end
// Shot.m
#import "Shot.h"
@implementation Shot
- (void)SetShot:(CGPoint *)point;
{
position.x = point->x;
position.y = point->y;
}
@end
When I try to call the SetShot
method, xcode gives me this warning:
method -SetShot not found(return type defaults to id)
Here is the call:
//CustomImageView.m
#import "CustomImageView.h"
@class Shot;
@implementation CustomImageView
-(id) initWithCoder:(NSCoder *)aDecoder
{
self.userInteractionEnabled = YES;
return self;
}
-(void) setInteraction
{
self.userInteractionEnabled = YES;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
Shot *shot;
[shot SetShot:point];
}
- (void)dealloc
{
[super dealloc];
}
@end
When I run the program, I get a fatal error when the method is called. Why is that?
Upvotes: 0
Views: 3621
Reputation:
There are three problems in your code. Firstly, you need to import Shot.h in your CustomImageView.m implementation file:
#import "Shot.h"
instead of simply forward-declaring the Shot
class:
@class Shot;
When the compiler sees a forward declaration, it becomes aware of the existence of that class but doesn’t yet know its attributes, declared properties, or methods — in particular, it doesn’t know that Shot
has a -SetPoint:
instance method.
Secondly, you’re not creating an instance of Shot
:
Shot *shot;
[shot SetShot:point];
This only declares that shot
is a pointer to Shot
but there’s no allocation/initialisation. You should create an object, i.e.:
Shot *shot = [[Shot alloc] init];
then use it:
[shot SetShot:point];
and, when you don’t need it any longer, release it:
[shot release];
Although it’s not clear what’s the benefit of creating a shot, setting its point, and then releasing it. Unless your code is a contrived example, you might want to rethink this behaviour.
Also, your -SetPoint:
method has a pointer to CGPoint
parameter but you’re passing a CGPoint
value (i.e., not a pointer) argument:
// point is not a pointer!
CGPoint point = [touch locationInView:self];
Shot *shot;
[shot SetShot:point];
I suggest you drop the pointer altogether, i.e.:
- (void)SetShot:(CGPoint)point;
{
position = point;
}
and maybe use a declared property instead of a manually implemented setter method.
Upvotes: 5
Reputation: 48398
You have not created an instance of Shot
; you have only created a pointer with:
Shot *shot;
You must allocate and initialize it:
Shot *shot = [[Shot alloc] init];
At some point you must import the header file Shot.h
as well.
Upvotes: 1