views:

65

answers:

2

I have an NSDate object which I use in the main thread of my iPhone app and I also reference it from a background thread, its defined like this:

//header
NSDate *currentDate;
@property (nonatomic, retain) NSDate *currentDate;

//implementation file
@synthesize currentDate;

Then in my app, I call a refreshData method which passes that object to another helper class to get some data from a remote service:

- (void) reloadData: (NSInvocationOperation*)operation  
{
    //...
    NSMutableArray *results = [managerHelper refreshForAddress: address 
                                                      timeFrom: fromDate
                                                        timeTo: self.currentDate];
    //...
}

(note the above call is on the background thread)

now, in side that helper class, I have added these lines

- (NSMutableArray*) refreshForAddress:(NSString *)address 
                            timeFrom:(NSDate*) fromDate 
                              timeTo:(NSDate*) toDate
{
    debugLog(@"retain count: %i", [toDate retainCount]);
    NSNumber *toTimeNumber = [[NSNumber alloc] initWithDouble: [toDate timeIntervalSince1970]*1000];
    debugLog(@"after retain count log");
}

But I get the classic error: "* -[__NSDate timeIntervalSince1970]: message sent to deallocated instance 0x71beea0"

And the logging says:

MyApp[5487:7903] retain count: 2 MyApp[5487:7903] * -[__NSDate timeIntervalSince1970]: message sent to deallocated instance 0x71beea0

So, as you can see the last log statement doesnt get called, but the retainCount is 2, how can this be when I get that error the line after the log call???

A: 

The way you initialize the NSDate returns an autorelease instance which will be dealocated automatically a the end of the event loop. Use [[NSDate date] retain] and don't forget to release it manually.

VdesmedT
`self.currentDate = ...` retains the object
tob
+1  A: 

You said you use two or more threads. So, you should define property as following way,

@property (retain) NSDate *currentDate;  ///< atomic default

This way will guarantee thread-safe for this property.

Edit:

Remove the "nonatomic" from @property, and it will behave as an atomic operation by default. The atomic operation will guarantee thread-safe behavior.

Toro
did you mean "retain"? or reatin?
Mark
also, would this explain the issue im getting?
Mark
Sorry, I type wrong. I mean "retain", and no "nonatomic". I think you have main thread and background thread. So, if two threads will use this property, I think it is important to guarantee thread safe.
Toro
ok I will change that and see if it helps
Mark