Getting “EXC_BAD_ACCESS”
I have an Address interface as this:
@interface AddressCard : NSObject
{
NSString *name;
NSString *email;
}
@property (copy, nonatomic) NSString *name, *email;
-(void) print;
-(void) setName:(NSString *) theName andEmail:(NSString *) theEmail;
-(void) dealloc;
@end
And implementation as:
#import "AddressCard.h"
@implementation AddressCard
@synthesize name, email;
-(void) setName:(NSString *) theName andEmail: (NSString *) theEmail
{
self.name = theName;
self.email = theEmail;
}
-(void) print
{
NSLog (@"==============================");
NSLog(@"| %-21s |", [self.name UTF8String]);
NSLog(@"| %-21s |", [self.email UTF8String]);
NSLog (@"==============================");
}
-(void) dealloc
{
[name release];
[email release];
[super dealloc];
}
@end
When I run it I keep getting an EXEC_BAD_ACCESS during the pool drain. I'm unable to find the cause and any help is appreciated. This is my first step into Objective-C 开发者_StackOverflow中文版so please bear with me.
thanks Sunit
Since the error occurs when draining the pool, I might be suspicious that you've already deallocated the object by that point, and the object is over-released (although generally you'll get a "malloc double free" error for this) or perhaps the memory has already been overwritten by something else. I'd suggest running it with zombies enabled, as in this answer — if you have Snow Leopard you can use the Zombies tool in Instruments from Xcode's Run menu. Good luck!
That example looks quite familiar - I just worked through that book myself! The code you've posted above is fine, so the problem must be elsewhere. You might try checking out the author's forum - the source code for each of the steps for that chapter is posted there.
As others have suggested, you might want to look for extra 'release' calls.
Since you are releasing the strings in your dealloc method it would appear that your AddressCard object assumes ownership of the strings but you use this line to define the properites:
@property (copy, nonatomic) NSString *name, *email;
Using copy means that your object is not retaining the strings. Try changing that line to this:
@property (retain, nonatomic) NSString *name, *email;
Using retain means that your object will retain the strings until you release them in your dealloc.
Hopefully that will solve the problem.
精彩评论