RubyMotion中的对象初始化 [英] Object initialization in RubyMotion

查看:192
本文介绍了RubyMotion中的对象初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是RubyMotion的新手,试图了解对象初始化的工作原理。假设有一个类和一个实例方法的简单类:

I am new to RubyMotion and trying to understand how object initialization works. Suppose a simple class with one class and one instance method:

class Something
  def self.getSomething
    BubbleWrap::HTTP.post("http://example.com") do |response|
      p response
    end
  end

  def getSomething
    BubbleWrap::HTTP.post("http://example.com") do |response|
      p response
    end
  end
end



,为什么要做以下工作:

Now, why does the following work:

Something.getSomething

下一个代码段不是很好,有时(运行此代码段,运行时崩溃了8次10次)。

And the next snippet not, well, sometimes (ran this snippet and the runtime crashed 8 out of 10 times).

something = Something.new
something.getSomething

我做错了。任何指向正确方向的指针?

I am doing it wrong. Any pointers in the right direction?

推荐答案

使用实例变量:

@something = Something.new
@something.getSomething

RubyMotion有一些与局部变量和块相关的错误。你分配给 something 然后调用 something.getSomething ,然后使用BubbleWrap的异步 HTTP.post 方法。 BubbleWrap HTTP块运行,但在此期间,您调用 something.getSomething 的方法已完成执行。由于 something 是一个局部变量,当方法退出时,它会收集垃圾。因此,当HTTP请求完成并且块被调用时,块不再存在。

RubyMotion has a handful of bugs related to local variables and blocks. You're assigning to something and then calling something.getSomething, which then uses BubbleWrap's asynchronous HTTP.post method. The BubbleWrap HTTP block runs, but in the meantime, the method you're calling something.getSomething from has completed execution. Since something is a local variable, it gets garbage collected when the method exits. So when the HTTP request completes and the block is called, the block no longer exists.

您可能会看到随机不一致的错误(以及一段时间的实际工作请求),因为每次,存储块的内存位置被回收else(或者在一段时间,它没有回收,所以所以块仍然存在)。当你使用一个实例变量时,不会发生这种情况,因为当调用方法完成执行时,实例变量会停止。

You're probably seeing random inconsistent errors (and once in a while an actual working request) because each time, the memory location where the block was stored was reclaimed for something else (or once in a while, it wasn't reclaimed at all so the block is still there). None of this happens when you use an instance variable instead, because when the calling method finishes execution, the instance variable sticks around.

我知道有几个问题已经提交(包括我自己),以获得这个固定。

This behavior is definitely unexpected; I know a couple issues have been filed (myself included) to get this fixed.

这篇关于RubyMotion中的对象初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆