【问题标题】:Call a method from another class when shake is detected检测到抖动时调用另一个类的方法
【发布时间】:2012-04-09 01:17:16
【问题描述】:

代码如下:http://min.us/mWdMO0n14

我是 Obj C 新手,所以我搜索了很多,但没有找到任何可以解决我的问题的东西。

我有 CalculatorViewController.h 和 .m,然后是 CalculatorBrain.h 和.m(斯坦福讲座)

在 CalculatorBrain.m 中,我有以下方法,所有变量在 CalculatorBrain 标头中定义为私有。

- (void)clearEverythingOnShakeGesture{
    operand = 0;
    waitingOperation = @"";
    waitingOperand = 0;
}

然后在 CalculatorBrain.m 中,我设置了一切以检测抖动,如下所示。我在抖动检测上方包含了一些代码,以便您有一个大致的了解。

@interface CalculatorViewController()
@property(nonatomic, retain) CalculatorBrain *brain;
@end

@implementation CalculatorViewController

@synthesize brain;
- (CalculatorBrain *)brain {
    if (!brain) {
        brain = [[CalculatorBrain alloc] init];
    }
    return brain;
}

-(BOOL)canBecomeFirstResponder{
    return YES;
}

-(void)viewDidAppear: (BOOL) animated{
    [super viewDidAppear:animated];
    [self becomeFirstResponder]; 
}

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (event.subtype == UIEventSubtypeMotionShake)
    {
        NSLog(@"SHAKE IT!");
        [brain clearEverythingOnShakeGesture]; //********** not sure how to call this.

    }
}

我不确定如何调用 [brain clearEverythingOnShakeGesture];,因为我收到错误“找不到类方法 +clearEverythingOnShakeGesture,默认返回类型 id”。但是,如果我将其设为类方法,则其中的变量是实例变量,这会产生另一个错误。非常感谢任何帮助。

【问题讨论】:

  • 两个建议: 1. 使方法静态。 2. 使用 [self.brain clearEverythingOnShakeGesture]。
  • 你试过 [self.brain clearEverythingOnShakeGesture]; ?为了消除关于什么是“大脑”的任何歧义,我会这样合成它:@synthesize brain = _brain; .

标签: iphone objective-c class private shake


【解决方案1】:

上面评论中发布的项目的 AppDelegate 是从一个 nib 构建计算器视图控制器,然后立即释放它。应用程序部分功能,但要在摇动手势上清除的 UILabel 属性此时为空。

此外,最好在私有类别中声明私有属性,使用 _underscore 别名合成它们,并在合成方法之外将它们称为 self.property。

【讨论】:

    【解决方案2】:

    你在#import-ing CalculatorBrain.h 吗?此外,您通过在 getter 中构建 CalculatorBrain 使用了一个很好的惰性初始化模式,但您没有在 motionBegan: 方法中调用 getter。尝试 [self.brain clearEverything ...] 获取大脑实例。

    我没有在代码中看到任何会让编译器认为你有类方法的东西。所以这很神秘。请仔细检查标题导入。你是正确的 clearEverything... 应该是一个实例方法。

    【讨论】:

    • 我已经按照你说的做了,我不再收到错误了。但是,当我在模拟器中选择摇动手势时,计算器不会自行清除。我知道 clearEverythingOnShakeGesture 方法本身有效,因为当我通过使用按钮调用它时,它工作正常。
    • 你是说motionBegan:模拟摇动手势时没有调用吗?如果是,您会在日志中看到 SHAKE IT 消息。查看stackoverflow.com/questions/150446/… 以检查您的代码是否有震动。
    • 我在日志中看到了这条消息,所以我知道摇晃有效。问题是,当检测到震动时,其他任何方法都不起作用。如果您想快速测试它,这是该项目。这将不胜感激。 min.us/mWdMO0n14
    • @AlexG 查看并修复了您的项目。问题不在于摇动手势,而是您当时组织主笔尖和校准笔尖的方式。想在 minus.com 上为您发布,但它不允许我上传文件夹。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多