开发者

EXC_BAD_ACCESS iOS error

开发者 https://www.devze.com 2023-03-08 07:27 出处:网络
I know, I know. I\'ve Google and searched here but can\'t figure out what\'s going on. Anyway, i\'m getting this error when using the following code, i\'m sure it\'s something small. I know it\'s to

I know, I know. I've Google and searched here but can't figure out what's going on.

Anyway, i'm getting this error when using the following code, i'm sure it's something small. I know it's to do with memory management and down to how i'm handling my object in the main method.

Here's my main code:

Person *p1 = [[Person alloc] init];
[p1 initWithFirstnam开发者_开发百科e:@"John" lastname:@"Doe" andAge:23];

outputText.text = [p1 getDetails]; // App crashes inside getDetails

Then in the person class here's the two relevant methods:

-(Person *)initWithFirstname:(NSString *)_firstname lastname:(NSString *)_lastname andAge:
(int)_age {
self = [super init];

if(self) {
self.firstname = _firstname;
self.lastname = _lastname;
self.age = _age;

}
return self;
}


-(NSString *)getDetails {
 return [NSString stringWithFormat:@"%@ %@, %@", firstname, lastname, age];
}


Judging by your init method, age is an int which means the format specifier is wrong. Try this:

-(NSString *)getDetails 
{
    return [NSString stringWithFormat:@"%@ %@, %d", firstname, lastname, age];
    //                                         ^^ format specifier for an int
}


You've written an initialization method, then called init twice. Just try:

Person *p1 = [[Person alloc] initWithFirstname:@"John" lastname:@"Doe" andAge:23];

outputText.text = [p1 getDetails];


You're first calling the default init of your newly allocated object. That init returns a pointer to your object which you store in p1. Then you call initWithFirstname:lastname:andAge: on p1, which is wrong as you've already called another initializer first. You're only supposed to run one initializer.

You need to do:

Person *p1 = [[Person alloc] initWithFirstname:@"John" lastname:@"Doe" andAge:23];

But your crash stems from the fact that you pass the number 23 to the format specifier %@. You need to use %d for the age instead. Also, you should retain the first and last name (and release them in your dealloc) to avoid any crashes later on when using non-const strings.

What happens is that because of %@, the NSLog tries to treat the 23 as a pointer to an object and wants to call the description method of the supposed object. But 23 is an invalid/unused address, and trying to access the memory at that "address" is what makes your app crash.

0

精彩评论

暂无评论...
验证码 换一张
取 消