开发者

NSDateComponents - EXC_BAD_ACCESS error

开发者 https://www.devze.com 2022-12-19 08:57 出处:网络
Basic question to which I\'m sure there is a simple answer. I\'m trying to get the timestamp of a photo. When I tr开发者_JS百科y to access the NSDateComponents to retrieve a specific date element (s

Basic question to which I'm sure there is a simple answer.

I'm trying to get the timestamp of a photo. When I tr开发者_JS百科y to access the NSDateComponents to retrieve a specific date element (say "day" for example), I get a EXC_BAD_ACCESS error.

First, the relevant bits of my code:

// formattedDateString is a string representing the "DateTimeOriginal" EXIF property extracted from the image   
NSDate *takenAt = [[NSDate alloc] initWithString:formattedDateString];
NSLog(@"date: %@", takenAt); // prints= date: 2010-01-10 03:25:00 -0500

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSLog(@"cal: %@", gregorian); // prints= cal: <__NSCFCalendar: 0x10020b570>

NSUInteger unitFlags =  (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit);      
NSDateComponents *components = [gregorian components: unitFlags 
                                            fromDate: takenAt
                               ];

int days = [components hour];
NSLog(@"comp: %@", days); // thrown error= Program received signal:  “EXC_BAD_ACCESS”

If I comment out the final line: NSLog(@"comp: %@", days); the code executes successfully.

I've tried a few variants on this but the bottom line is that any time I send a message to components to access a property the "EXC_BAD_ACCESS" error is raised.

The research I did seems to indicate that this is typically the result of an uninitialized pointer or an object that I've tried to release that isn't mine to release. From what I can tell that's not the case here.

What am I missing?

Thanks in advance for shedding some light on this for me. This is one of my first explorations in Objective-C.

NSDateComponents class reference.


You are using %@ as the format-specifier for an integer. You need to use %d.

When you use %@, the NSLog function will treat the argument as an object, and send it the description message. What really happens, is that the runtime tries to dereference the argument (the integer) but because it is not a valid pointer, you get an EXC_BAD_ACCESS exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号