0

I'm trying to figure out how to centralize a method that I use in a few of my ViewControllers. I already had a singleton that I was using for some variables. I called the singleton class Shared.

I moved my method to the Shared class and tried calling it like so:

m.createdAt = [Shared getUTCFormateDate:[messageObject objectForKey:@"created_at"]];

It's giving me an exception saying that the selector doesn't exist when it tries to call it.

I have already imported Shared.h. Any other thoughts would be appreciated.

wattostudios
  • 8,666
  • 13
  • 43
  • 57
Jody G
  • 583
  • 8
  • 21
  • If you're going to use a Singleton, basically the only way to do it is like in every other iOS app -- simply use Matt Gallagher's famous singleton macro file: http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html Link to the actual file: http://projectswithlove.com/projects/SynthesizeSingleton.h.zip Many problems in programming ARE SOLVED: this is one of them. – Fattie Apr 30 '11 at 20:39

2 Answers2

1

If your class is named "Shared" then it looks like you are trying to call a class method rather than an instance method. So, you need to declare the method with + instead of -.

Richard Brightwell
  • 3,012
  • 2
  • 20
  • 22
0

here is the correct pattern for creating a Singleton in objective-c: (Ill use an example of a User object.. taken from code I have open in front of me). also, please note that there is a difference between Singleton classes and Static Class methods, as discussed here.. Difference between static class and singleton pattern?

in the .h file, declare a static method that returns an instance of your class.

+(User *) currentUser;

in the .m file, create a static variable that holds your instance

static User * _user;

then, in your .m class, create your "public" static accesor GET that returns or instantiates and returns your static variable

+ (User *) currentUser
    {

        if (!_user) 
        {
            _user =[[User alloc]init];
            // ... init the singleton user properties and what not
            // ...
        }

        return _user;   

    }

then, when you want to call on your Singleton class you just make sure that User.h is imported and call [[User currentUser] someMethodorProperty];

enjoy

Community
  • 1
  • 1
Jason Cragun
  • 3,233
  • 1
  • 26
  • 27
  • Thanks. I already had a working Singleton though that I've been using with shared variables. This is where I'm trying to call a Shared method. I had forgotten the + sign. – Jody G Apr 30 '11 at 16:46