[英]EXC_BAD_ACCESS iOS error
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.
我知道这与 memory 管理有关,以及我如何在主要方法中处理我的 object。
Here's my main code:这是我的主要代码:
Person *p1 = [[Person alloc] init];
[p1 initWithFirstname:@"John" lastname:@"Doe" andAge:23];
outputText.text = [p1 getDetails]; // App crashes inside getDetails
Then in the person class here's the two relevant methods:然后在人 class 中,这是两个相关的方法:
-(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.从您的
init
方法来看, age
是一个int
,这意味着格式说明符是错误的。 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.您编写了一个初始化方法,然后调用了两次
init
。 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.您首先调用新分配的 object 的默认
init
。 That init
returns a pointer to your object which you store in p1
.该
init
返回指向您存储在p1
中的 object 的指针。 Then you call initWithFirstname:lastname:andAge:
on p1
, which is wrong as you've already called another initializer first.然后你在
p1
上调用initWithFirstname:lastname:andAge:
,这是错误的,因为你已经先调用了另一个初始化器。 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 %@
.但是您的崩溃源于您将数字
23
传递给格式说明符%@
的事实。 You need to use %d
for the age instead.您需要使用
%d
来代替年龄。 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.此外,您应该保留名字和姓氏(并在您的
dealloc
中释放它们)以避免以后在使用非常量字符串时发生任何崩溃。
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.由于
%@
,NSLog 尝试将 23 视为指向 object 的指针,并希望调用假定的 object 的description
方法。 But 23 is an invalid/unused address, and trying to access the memory at that "address" is what makes your app crash.但是 23 是一个无效/未使用的地址,并且试图在该“地址”访问 memory 是导致您的应用程序崩溃的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.