views:

52

answers:

3

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 release-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!

A: 

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.

KennyTM
I have in .h@property int numberOfSides;@property int minimumNumberOfSides;@property int maximumNumberOfSides;And in .m:@synthesize numberOfSides;@synthesize minimumNumberOfSides;@synthesize maximumNumberOfSides;Those setters/getters work just fine. My problem is with allocating and releasing. I thought nothing special had to be done since none of my ivars are objects.
Mark
shouldn't this cause another kind of issues (e.g. like unknown selector)? I would think about autorelease pool, too...
ShinTakezou
@Mark: I can't see any memory management bugs in your posted code.
KennyTM
@Shin: Unknown selector is also EXC_BAD_ACCESS. That's why @Mark should post the console message. The EXC_BAD_ACCESS code is useless.
KennyTM
A: 

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!)

Mike Howard
+5  A: 
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.

dreamlax
That did it! GOod eye!
Mark
+1 expecially for "your compiler should have warned ..."... we learn: never ignore warnings!
ShinTakezou