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, 开发者_StackOverflowits 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???
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.
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.
精彩评论