Obj-C: calling release/dealloc causes EXC_BAD_ACCESS
Here is my custom class:
PolygonShape : NSObject {
int numberOfSides;
int minimumNumberOfSides;
int maximumNumberOfSides;
}
My custom init method:
- (id)initWithNumberOfSides:(int)sides minimumNumberOfSides:(int)min maximumNumberOfSides:(int)max {
if (self = [super init]) {
[self setMinimumNumberOfSides:min];
[self setMaximumNumberOfSides:max];
[self setNumberOfSides:sides];
}
return self;
}
My dealloc method:
- (void) dealloc {
NSLog("Calling dealloc");
[super dealloc];
}
My sample code that crashes:
PolygonShape *shape1 = [[PolygonShape alloc] initWithNumberOfSides:6 minimumNumberOfSides:5 maximumNumberOfSides:9];
[shape1 release];
I've alloc-ed a PolygonShape increasing the retain count by 1 and then re开发者_开发技巧lease-ing should decrement it to 0 and call dealloc, printing that message to NSLog but I just get EXC_BAD_ACESS. I'm able to access and change the fields in my object after creating it so everything up until there works. Many thanks for the help!
NSLog("Calling dealloc");
You are passing a regular C string, rather than an NSString. You need to do this:
NSLog(@"Calling dealloc");
Your compiler should have warned you about passing an incompatible pointer.
Have you added these into the @interface
...
@property(assign) int numberOfSides, minimumNumberOfSides, maximumNumberOfSides;
and these into the @implementation
?
@synthesize numberOfSides, minimumNumberOfSides, maximumNumberOfSides;
The setters won't be generated automatically unless you explicitly @synthesize
it.
What line does it crash on? Could the error be in one of the methods you call in initWithNumberOfSides?
If doing "build and debug" to find where it crashes doesn't help, I'd turn on NSZombieEnabled to find the problem (don't forget to switch it off again!)
精彩评论