user440096
user440096

Reputation:

dateFromString not working with the string I supply

Getting a crash when trying to pass the string into NSDateFormatter dateFromString method.

I checked out the docs but I dont see anything to explain what is going wrong.

        NSError * errorX;

    NSDictionary * attributesDict = [[fileManager attributesOfItemAtPath:imgPath error:&errorX ] retain];

    NSString *theDate = [[attributesDict objectForKey:@"NSFileCreationDate"] retain]; 

    [NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];

    NSDate *dateFromString = [[NSDate alloc] init];
    dateFromString = [dateFormatter dateFromString:theDate];

Crash comes from the last line.

erminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDate length]: unrecognized selector sent to instance 0x1bd380'

Anybody able to point me where I've gone off track?

Thanks, -Code

Upvotes: 0

Views: 789

Answers (4)

dariaa
dariaa

Reputation: 6385

Are you sure that [attributesDict objectForKey:@"NSFileCreationDate"] returns an NSString object? It looks like it returns an NSDate;

Upvotes: 0

Jason Coco
Jason Coco

Reputation: 78343

The object returned from the file system is an NSDate, not an NSString. You already have a date object, so there's no need to try and convert it back into a date.

The crash data you posted tells you exactly why you crashed. Your app sent the length message to an instance of a date object, and the date object doesn't respond to that message (i.e., NSDate has no -length method). We know that dateFromString: is expecting a string and needs to parse the string, so we can assume that it needs to query the string's length. So you can see, you already have an actual date object.

Upvotes: 2

Ecarrion
Ecarrion

Reputation: 4950

Looks like this line

 NSString  * theDate = [[attributesDict objectForKey:@"NSFileCreationDate"] retain];

it's already returning you a NSDate instead of a string.

If you're getting this info trough the web, depending on the formatting, some json parsers cast the object to an NSDate automatically.

Upvotes: 0

Firoze Lafeer
Firoze Lafeer

Reputation: 17143

[attributesDict objectForKey:@"NSFileCreationDate"] will return an NSDate, not an NSString. So at that point, you already have the NSDate you are looking for, there is no need to use NSDateFormatter to parse it. In fact, you can't of course because dateFromString: requires a string.

BTW, you have a couple memory management issues here, unrelated to your question.

Upvotes: 3

Related Questions