views:

25

answers:

1

Hi,

I'm initializing a NSCalendar in viewDidLoad like this:

gregorian = [NSCalendar currentCalendar];

The calendar is declared in the corresponding .h file like this:

NSCalendar *gregorian;

When accessing the calendar from a method my app crashes:

- (void)someMethod{
  unsigned int unitFlags;
  unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
  [gregorian 
    components:unitFlags 
    fromDate:[NSDate date] 
    toDate:[NSDate date] 
    options:0];
}

This is what seems relevant from the crash log:

Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000000000015
Crashed Thread: 0 Dispatch queue: com.apple.main-thread

Application Specific Information:
objc_msgSend() selector name: components:fromDate:toDate:options:
iPhone Simulator 225, iPhone OS 3.2 (iPad/7W367a)

Any ideas ?

Thanks

A: 

You're not retaining your calendar when assigning it to "gregorian" so it is gone by the time you access it.

Joshua Nozzi
Thanks for your answer. I'm still wondering why I can do the same thing with a UIView and it works (without retaining) ?
DeepSeaFish
If you're not retaining an autoreleased object you plan to stick around as an instance variable, you're doing it wrong. We'll need to see the code that seems to be working to answer that question. In general, however, memory management bugs can appear to behave strangely (ie, they don't always crash right away or reliably). In the code you posted, however, you're not retaining the calendar object then trying to access it later and that's an error.
Joshua Nozzi
DeepSeaFish: I once had a problem with Bindings in Cocoa where I was using the autoreleasing constructor (`arrayWith…:`) to create an array my controller owned, and failing to retain it. Thus, this array was due for death—it had no net retains. Then I loaded a nib. I had a view in the nib bound to the property that exposed the array. When the view got unarchived, its binding retained the array and saved it from death. Sometimes you can't rely on the bug manifesting, but it's still a bug.
Peter Hosey