Search code examples
iosobjective-cclassglobalclass-design

Creating an objective c global class


I'm sure I'm just missing something simple here, but can't find the answer though I looked in the other examples here, my code seems to be the same. I'm trying to define a global class with some methods that I can access from the other classes in my project. I can define it, but can not access the methods from my other classes, though I always import the global class header to the class where I want to use the method. Heres the code: 1st The Global class def:

#import <Foundation/Foundation.h>

@interface GlobalMethods : NSObject {}

- (unsigned long long)getMilliSeconds:(NSDate*)d;

- (NSDate *)getDateFromMs:(unsigned long long)ms;

@end

#import "GlobalMethods.h"

@implementation GlobalMethods

//SET DATE TO MILLISECONDS 1970 EPOCH

- (unsigned long long)getMilliSeconds:(NSDate*)d
{
    unsigned long long seconds = [d timeIntervalSince1970];

    unsigned long long milliSeconds = seconds * 1000;


    return milliSeconds;
}

// GET DATE FROM MILLISECONDS 1970 EPOCH

- (NSDate *)getDateFromMs:(unsigned long long)ms
{
    unsigned long long seconds = ms / 1000;
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970: seconds];

    return date;
}


@end

and then where I want to use my methods in another class:

#import "GlobalMethods.h"


// GET MILLISECONDS FROM 1970 FROM THE PICKER DATE
    NSDate *myDate = _requestDatePicker.date;

    milliSeconds = [self getMilliSeconds: myDate];

Error is : No visable interface for viewcontroller declares the selector getMilliSeconds.

Thanks for the help with this.


Solution

  • You are trying to call the getMilliSeconds: method (which is an instance method of the GlobalMethods class) on an instance of your view controller class. That is the cause of the error.

    As written you need to change this line:

    milliSeconds = [self getMilliSeconds: myDate];
    

    to:

    GlobalMethods *global = [[GlobalMethods alloc] init];
    milliSeconds = [global getMilliSeconds:myDate];
    

    A better solution is to first change all of the instance methods of your GlobalMethods class to be class methods. In other words, in both the .h and .m file for GlobalMethods, change the leading - to a + for both methods.

    Then in your view controller you can do:

    milliSeconds = [GlobalMethods getMilliSeconds:myDate];