[MacRuby-devel] Accessing Obj-C InstVars from Ruby

Brian Chapados chapbr at gmail.com
Mon Mar 30 12:56:44 PDT 2009


In this case, you could use the KVC[1] (key-value coding)  accessor
(#valueForKey:) to access the ivar.

class Example
  def methodB
    self.valueForKey("instVarB")
  end
end

[1]: http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/Concepts/Compliant.html

Brian

On Mon, Mar 30, 2009 at 9:27 AM, Edward Hynes <ehynes at dharmagaia.com> wrote:
> Is there a way to access instance variables defined in an Objective-C class
> from a Ruby extension?  I'm porting some of Apple's example code to MacRuby
> as a learning experience and would like to do so incrementally.  Porting the
> code one class at a time works fine, but for some of the larger classes I'd
> like to port them a few methods at a time.  Here's an example of what's
> happening
>
>
> --- Example.h ---
>
>   @interface Example : NSObject {
>       NSString *instVarA;
>       NSString *instVarB;
>    }
>
>   - (NSString *)methodA;
>   @end
>
>
> --- Example.m ---
>
>   #import "Example.h"
>
>   @implementation Example
>     - (id)init {
>       if (self = [super init]) {
>         instVarA = @"instVarA";
>         instVarB = @"instVarB";
>       }
>       return self;
>     }
>
>     - (NSString *)methodA {
>       return instVarA;
>     }
>
>   @end
>
>
> --- Example.rb ---
>
>   class Example
>     def methodB
>       @instVarB
>     end
>   end
>
>
> Then at runtime, when I execute the following...
>
>   example = Example.alloc.init
>   puts example.methodA.inspect
>   puts example.methodB.inspect
>
>
> .. I get
>
>   "instVarA"
>   nil
>
>
> How do I access InsVarB from Ruby?
>
> Thanks,
> Ed
>
>
> _______________________________________________
> MacRuby-devel mailing list
> MacRuby-devel at lists.macosforge.org
> http://lists.macosforge.org/mailman/listinfo.cgi/macruby-devel
>


More information about the MacRuby-devel mailing list