stRs232Timer* pEvent;
pEvent = (stRs232Timer*)[m_cAppIdMap objectForKey:[NSNumber numberWithUnsignedShort:wTimerIds]];
我收到EXC_BAD_ACCESS错误。为什么会这样?
编辑:
-(BOOL)createTimer
{
stRs232Timer* pEvent = malloc(sizeof(stRs232Timer));
pEvent->bPersistent = YES; // setup timer structure
//pEvent->pStack = pStack;
pEvent->wAppTimerId = 95;
pEvent->uPeriod = 50;
pEvent->bStopped = NO;
pEvent->uExpirationTime = 10;
NSLog(@"bPersistent:%d",pEvent->bPersistent);
NSLog(@"wAppTimerId:%d",pEvent->wAppTimerId);
NSLog(@"uPeriod:%d",pEvent->uPeriod);
NSLog(@"bStopped:%d",pEvent->bStopped);
NSData* myData = [NSData dataWithBytes:(void*)pEvent length:sizeof(stRs232Timer*)];
wTimerId = 99;
pEvent->uPeriod = 51;
myData = [NSData dataWithBytes:(void*)pEvent length:sizeof(stRs232Timer*)];
[m_cAppIdMap setObject:myData forKey:[NSNumber numberWithUnsignedShort:wTimerId]];
wTimerId = 96;
pEvent->uPeriod = 52;
myData = [NSData dataWithBytes:(void*)pEvent length:sizeof(stRs232Timer*)];
[m_cAppIdMap setObject:myData forKey:[NSNumber numberWithUnsignedShort:wTimerId]];
wTimerId = 97;
pEvent->uPeriod = 53;
myData = [NSData dataWithBytes:(void*)pEvent length:sizeof(stRs232Timer*)];
[m_cAppIdMap setObject:myData forKey:[NSNumber numberWithUnsignedShort:wTimerId]];
wTimerId = 98;
pEvent->uPeriod = 54;
myData = [NSData dataWithBytes:(void*)pEvent length:sizeof(stRs232Timer*)];
[m_cAppIdMap setObject:myData forKey:[NSNumber numberWithUnsignedShort:wTimerId]];
wTimerId = 95;
pEvent->uPeriod = 55;
myData = [NSData dataWithBytes:(void*)pEvent length:sizeof(stRs232Timer*)];
[m_cAppIdMap setObject:myData forKey:[NSNumber numberWithUnsignedShort:wTimerId]];
NSLog(@"The dictionary count now is:%d",[m_cAppIdMap count]);
NSLog(@"The dictionary values now is:");
NSLog(@"%@",m_cAppIdMap);
[m_cPendingEventList addObject:myData];
NSLog(@"EventList:%@",m_cPendingEventList);
[self StopTimer:99];
return YES;
}
-(BOOL)StopTimer:(unsigned short)wTimerIds
{
NSLog(@"Into the StopTimer!!");
stRs232Timer* pEvent;
BOOL bReturn = NO;
pEvent = (stRs232Timer*)[m_cAppIdMap objectForKey:[NSNumber numberWithUnsignedShort:wTimerIds]];
if ([theLock tryLock]) {
int cnts = [m_cAppIdMap count];
NSLog(@"The count is:%d",cnts);
if(pEvent!=nil)
{
pEvent->bStopped = YES;
[m_cAppIdMap removeObjectForKey:[NSNumber numberWithUnsignedShort:wTimerIds]];
bReturn = YES;
}
}
NSLog(@"My Dictionary value now is:%@",m_cAppIdMap);
[theLock unlock];
return bReturn;
}
我调试了代码以查看它导致此异常的位置。[m_cAppIdMap removeObjectForKey:[NSNumber numberWithUnsignedShort:wTimerIds]]; 在stopTimer里面。它出来了。
stRs232Timer是一个指向结构的指针,该结构使用NSData作为NSObject存储在NSDictionary上。
答案 0 :(得分:3)
你确定那个代码崩溃了吗?如果wTimerIds
是无符号短,则如果密钥不存在,则字典将返回nil
。即使没有定义字典,向nil
对象发送消息也是有效的,因此不会导致崩溃。
因此,我认为:
这次事故发生在其他地方
2. wTimerIds
不是无符号的短
答案 1 :(得分:2)
m_cAppIdMap
可能过早被释放。您可以运行Profiler(使用Zombies工具),如果是这种情况,您将收到一条错误消息,说明在尝试调用objectForKey时已将消息发送到已释放的对象