Jody G
Jody G

Reputation: 583

Calling a public method

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.

Upvotes: 0

Views: 346

Answers (2)

Jason Cragun
Jason Cragun

Reputation: 3233

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

Upvotes: 0

Richard Brightwell
Richard Brightwell

Reputation: 3012

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 -.

Upvotes: 1

Related Questions