Search code examples
rubyrubymotion

Globally accessible attribute in UIViewController instances


In my RubyMotion app I would like to have a attribute, called access_token, accessible in every UIViewController instance.

All my controllers are either a subclass of TableController or AppController.

I tried creating an attr_accessor for TableController and AppController, though the problem is that assigning a new value will not be set for TableController or AppController at the same time.

How could I achieve this?


Solution

  • I personally use class variables for things like this, since iOS apps are not multi-user. Taking advantage of the fact that inherited classes share class variables, @@access_token will have the same value for all of your UIViewController subclasses (or your own subclass if you prefer).

    I have something similar to this:

    # Reopen and extend
    class UIViewController # Actually I prefer UIViewController.class_eval do
      @@access_token = nil # This will have the same value for all UIViewController children
    
      def self.access_token=(value)
        @@access_token = value
      end
    
      def self.access_token
        @@access_token
      end
    end
    

    In reality, I would build a class that holds properties including and in addition to the token.