Codeguy007
Codeguy007

Reputation: 891

Receiving NSInvalidArgumentException when calling class

I'm just learning Objective-c and I am trying to create a class the generates the current date in a MySQL Timestamp format. The code compiles fine but I am getting the following error.

012-09-07 08:21:00.368 jsonclient[6831:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[getcurrenttime toString]: unrecognized selector sent to class 0x36a9c'

I'm sure this is a simple answer but I have been unable to find it myself. Here's my call to the class followed by the header and .m file.

NSString* CurrentDate = [getcurrenttime toString];



#import <UIKit/UIKit.h>

@interface getcurrenttime : NSObject {
    NSString *toString;
}

+(NSString*) toString;

@end




#import "getcurrenttime.h"

@implementation getcurrenttime

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

- (NSString*) toString {


    NSDate *now =[NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    toString = [formatter stringFromDate:now];

    return toString;
}
@end

Upvotes: 0

Views: 74

Answers (2)

alloc_iNit
alloc_iNit

Reputation: 5183

You have to first initialize the object.

getcurrenttime *objGetTime = [[getcurrenttime alloc] init];

And then call its method...

NSString* CurrentDate = [objGetTime toString];

You have done in case, you want a global method to call...

NSString* CurrentDate = [getcurrenttime toString];

But put "-" instead of "+" in getcurrenttime.m file.

+ (NSString*) toString 
{
    NSDate *now =[NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *toString = [formatter stringFromDate:now];
    return toString;
}

Upvotes: 0

swehrli
swehrli

Reputation: 141

There is a mismatch between the interface and implementation of your class. The simplest solution is to change the follwing line:

+ (NSString*) toString

Notice the + instead of -, which indicates a class method.

Upvotes: 2

Related Questions