4

我向 String 类添加了一个额外的方法。我想稍后使用这个方法,但是我得到一个 no Method 错误。

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 实现的。

编辑:

当我克隆模型返回的字符串时,存在添加的方法

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"
4

1 回答 1

4

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

class NSString 
   def as_file_full_path
       NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)   [0].stringByAppendingPathComponent(self)    
   end
end
于 2013-02-28T11:09:58.960 回答