简体   繁体   中英

Strange BAD_ACCESS when printing NSInteger

this is my first time asking something here, so don't be too harsh on me please :-). I have a strange "bad access" issue. In a class of mine I have a NSInteger along with a few other members. I override the - (NSString *)description method to print the values of everything like so (omitted the unrelevant part):

- (NSString *)description {
    return [NSString stringWithFormat:@"Duration:%d", duration];
}

and then I print that using NSLog(@"%@", myObject) which is giving me EXC_BAD_ACCESS without any log messages, regardless of the NSZombieEnabled.

  • I have double checked the order of all formatting specifiers and parameters - it's correct.
  • I tried changing the format specifier to %i and %@ and didn't get any result
  • When I init my object I don't initialize duration. Later, I assign it through a property @property NSInteger duration . So I tried initializing the duration to 0 in my init method but to no avail.
  • If I box duration to a NSNumber prior to printing, it works.
  • When I remove the duration and leave all the other ivars it works again.

I'm stumped, what am I doing wrong here? Can you help me?

Thanks a lot!

EDIT: To summarize, It seems this is caused by differences between 32 and 64 bit platforms, because it's fine when run on an iphone 4 and has issues only when run in the simulator. I tried 3 different approaches - using %d and %i with the NSInteger variable itself, using %qi and using %ld / %lx and I also tried to cast to int and long with the various format specifiers. Every time I can run on the device, but get EXC_BAD_ACCESS in the simulator.

这里唯一的猜测:在您的情况下,NSInteger可能是64位,而%i(以及%d)期望使用32位整数,则可以尝试%qi或(似乎更好的)强制转换该值。

When you run the app in the debugger, where exactly is the signal raised? Xcode will show you the precise line and stack of the problem.

When you are sure the crash happens in the stringWithFormat: method it's probably a matter of format specifiers. Apple's String Programming Guide contains information on how to handle NSInteger in a safe and platform independent way.

也许您需要合成您的财产?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM