尝试打印结构变量Objective C时出错


-(BOOL)ChangeTimer:(unsigned short)wTimerIds withPeriod:(uint8_t)uPeriod
{
 stRs232Timer*   pEvent;
    NSLog(@"Into the changeTimer");
    NSLog(@"%d",wTimerIds);
    pEvent = (stRs232Timer*)[[m_cAppIdMap objectForKey:[NSNumber numberWithUnsignedShort:wTimerIds]]bytes];
    NSLog(@"bPersistent:%d",pEvent->bPersistent);
    NSLog(@"wAppTimerId:%d",pEvent->wAppTimerId);
    NSLog(@"uPeriod:%d",pEvent->uPeriod);
    NSLog(@"bStopped:%d",pEvent->bStopped);
    //NSLog(@"%@",pEvent);  
    if(pEvent!=nil){
        pEvent->bStopped = NO;
        pEvent->uPeriod = uPeriod;
        NSLog(@"completed");
    }   
    NSLog(@"The dict is:%@",m_cAppIdMap);
    NSLog(@"jsagxs:%@",m_cAppIdMap);
    return YES;
}

如果我删除上面代码中的注释,我会得到一个错误EXC_BAD_ACCESS。为什么会这样呢?

当您使用"%@"格式说明符时,您告诉运行时在相关指针上调用-descriptionWithLocale:-description方法,该指针的类被暗示为NSObject的子类。

结构不是Objective-C对象,因此没有-descriptionWithLocale:-description方法。这就是导致EXC_BAD_ACCESS的原因。

您应该使用%p来打印出不指向Objective-C对象的指针。

格式说明符%@的工作原理是期望NSObject子类,并调用descriptionWithLocale:description(如果不存在descriptionWithLocale(以获得描述对象的NSStringstRs232Timer只是一个C结构,而不是一个Objective C对象。当运行时试图将其视为对象时,事情就会爆炸,正如您所看到的那样。

请尝试使用%p说明符,它只会打印项的地址(即带有0x前缀的指针值(。

最新更新