creating a method available in all UIViewController classes

Discussion in 'iOS Programming' started by johnmerlino, Nov 13, 2011.

  1. johnmerlino macrumors member

    Joined:
    Oct 22, 2011
    #1
    Hey all,

    When a user logs in, I want to store that user instance in a method called currentUser. And in all my UIViewController classes, I would like to access certain properties of the currentUser, such as its email and id. I tried creating a category, but it would not allow me to synthesize because it doesnt allow instance variables. I do not want to subclass. Is there another way to do this?

    thanks for response
     
  2. chown33, Nov 13, 2011
    Last edited by a moderator: Nov 13, 2011

    chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #2
    in essence, I am looking something similar to a ruby module or php namespace.

    Define a singleton class: MyCurrentUser. Put everything there.

    If you had multiple users, then a singleton object/class might be a problem. But if there's always exactly one current user (or none), then a singleton is a perfectly fine solution, and doesn't need subclassing.
     
  3. mduser63 macrumors 68040

    mduser63

    Joined:
    Nov 9, 2004
    Location:
    Salt Lake City, UT
    #3
    I think chown33's suggestion is a good one, and is probably the way to go. Your idea of a category on UIViewController probably isn't really the best approach.

    That said, I thought you might be interested to know that it's possible to sort of "fake" adding instance variables in categories using Objective-C runtime functions. See the documentation here.
     
  4. jnoxx macrumors 65816

    jnoxx

    Joined:
    Dec 29, 2010
    Location:
    Aartselaar // Antwerp // Belgium
    #4
    Look up
    "SynthesizeSingleton"
    It's a header file someone created (for iOS5, need to change the release method to "oneway release".
    If you follow it's documentation, you can create an instance of a class that is hold in memory thorough your entire application.
    So if you have a Singleton of CurrentUser, and make his property's via a property public available via it's getters/setters.
    You can acces this instance in any class, with [[CurrentUser sharedCurrentUser] currentUser].properties
    Go look up a bit ^_-
     

Share This Page