Rubymotion:添加方法的NoMethodError

时间:2013-02-28 08:20:57

标签: rubymotion

我在String类中添加了一个额外的方法。我想稍后使用此方法,但我得到一个没有方法错误。

class String
   def as_file_full_path
      NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)   [0].stringByAppendingPathComponent(self)    
  end
end

当我在REPL中尝试以下操作时,它可以工作:

 (main)> "image.jpg".as_full_path
  => "/Users/user/Library/Application Support/iPhone Simulator/6.1/Applications/30D186A9-B1C7-4377-AE91-0D14BD3B4A6D/Documents/image.jpg"

但是当我在我的模型类上调用一个方法时,它不再起作用了:

 (main)> w = Word.first
  => #<Word:0x94d7df0>
 (main)> w.filename
  => "2C86A58A-A92A-4A0F-B26C-0F5F583E142C.caf"
 (main)> w.filename.class
  => String
 (main)> w.filename.as_full_path
 2013-02-28 09:17:55.935 project[74283:c07] undefined method `as_full_path' for "2C86A58A-A92A-4A0F-B26C-0F5F583E142C.caf":String (NoMethodError)
 => NoMethodError: undefined method `as_full_path' for "2C86A58A-A92A-4A0F-B26C-0F5F583E142C.caf":String

该模型使用NanoStore :: Model。

实现

编辑:

当我克隆模型返回的String时,添加的方法 存在。

w.filename.dup.as_full_path
=> "/Users/user/Library/Application Support/iPhone Simulator/6.1/Applications/30D186A9-B1C7-4377-AE91-0D14BD3B4A6D/Documents/2C86A58A-A92A-4A0F-B26C-0F5F583E142C.caf"

1 个答案:

答案 0 :(得分:4)

问题解决了!由于某种原因,扩展String类并不总是有效。我认为NanoStore由于某种原因不会返回“真正的”红宝石字符串。 通过将“String”替换为“NSString”来解决它:

class NSString 
   def as_file_full_path
       NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)   [0].stringByAppendingPathComponent(self)    
   end
end