【问题标题】:Why is xcode giving me a "method not found" error?为什么 xcode 给我一个“找不到方法”的错误?
【发布时间】:2011-09-19 03:51:06
【问题描述】:

我有一个名为Shot 的对象,它是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

当我尝试调用SetShot 方法时,xcode 给了我这个警告:

方法 -SetShot 未找到(返回类型默认为 id)

来电:

//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

当我运行程序时,调用该方法时出现致命错误。这是为什么呢?

【问题讨论】:

  • 我强烈建议您接受 Bavarious 解释清楚的答案。

标签: iphone xcode methods call


【解决方案1】:

#import "Shot.h"

代替:

@class Shot;

【讨论】:

    【解决方案2】:

    您还没有创建Shot 的实例;你只创建了一个指针:

    Shot *shot;
    

    你必须分配和初始化它:

    Shot *shot = [[Shot alloc] init];
    

    有时您还必须导入头文件Shot.h

    【讨论】:

    • anon 的回答是眼前的问题,但这也是一个重大错误。
    • 感谢您的回复。非常感谢!
    【解决方案3】:

    您的代码存在三个问题。首先,您需要在 CustomImageView.m 实现文件中导入 Shot.h:

    #import "Shot.h"
    

    而不是简单地向前声明Shot 类:

    @class Shot;
    

    当编译器看到前向声明时,它会意识到该类的存在,但还不知道它的属性、声明的属性或方法——特别是,它不知道Shot 有一个@ 987654326@实例方法。

    其次,您没有创建Shot的实例:

    Shot *shot;
    [shot SetShot:point];
    

    这仅声明 shot 是指向 Shot 的指针,但没有分配/初始化。您应该创建一个对象,即:

    Shot *shot = [[Shot alloc] init];
    

    然后使用它:

    [shot SetShot:point];
    

    当你不再需要它时,释放它:

    [shot release];
    

    虽然尚不清楚创建镜头、设定目标然后释放它有什么好处。除非您的代码是一个人为的示例,否则您可能需要重新考虑这种行为。

    此外,您的 -SetPoint: 方法有一个指向 CGPoint 参数的指针,但您传递的是 CGPoint 值(即,不是指针)参数:

    // point is not a pointer!
    CGPoint point = [touch locationInView:self];
    Shot *shot;
    [shot SetShot:point];
    

    我建议你完全放弃指针,即:

    - (void)SetShot:(CGPoint)point;
    {
        position = point;    
    }
    

    也许使用declared property 代替手动实现的setter 方法。

    【讨论】:

    • 我没有意识到你可以做到这一点......我的错。我以为你必须这样分配它。
    • 非常感谢。您的回复对我帮助很大!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多