检查变量是否包含内存地址

时间:2022-04-15 23:08:53

My game has a method that receives a string. Since iOS7, it begun crashing sometimes in it.

我的游戏有一个接收字符串的方法。从iOS7开始,它有时会开始崩溃。

In the method, I call lowercaseString on that string, and then it crashes with an EXC_BAD_ACCESS.

在该方法中,我在该字符串上调用lowercaseString,然后它与EXC_BAD_ACCESS崩溃。

-(void)changeDirection:(NSString *)_direction {
    if (![[direction lowercaseString] isEqualToString:[_direction lowercaseString]]) {

    }
}

Something that I noticed was that these times this string seems to be a memory address:

我注意到的一点是,这些字符串似乎是一个内存地址:

检查变量是否包含内存地址

Which explains why is it crashing - I'm calling lowercaseString on a memory address.

这解释了它崩溃的原因 - 我在内存地址上调用了lowercaseString。

Right now, the most logical solution would be to see why is this method receiving a memory address instead of an actual string, I guess.

现在,最合乎逻辑的解决方案是看看为什么这个方法接收内存地址而不是实际的字符串,我想。

However, for now, I want to make a quick workaround, which leads to this question:

但是,就目前而言,我想快速解决这个问题,这导致了这个问题:

How can I detect whether the given parameter is an actual string object like @"Hello" or a memory address?

如何检测给定参数是否是@“Hello”或内存地址等实际字符串对象?

1 个解决方案

#1


3  

Objects live on the heap, what you are calling NSString is actually a pointer to it. And a pointer is a memory address, so that's expected behavior not a issue.

对象存在于堆上,你所谓的NSString实际上是指向它的指针。指针是一个内存地址,因此预期的行为不是问题。

EXC_BAD_ACCESS means that you are accessing the memory in a bad way, i.e. the memory address you are pointing to is not valid memory.

EXC_BAD_ACCESS表示您正在以错误的方式访问内存,即您指向的内存地址不是有效内存。

This can happen when you try to access a dangling pointer (i.e. a pointer to an object that was already released) or an uninitialized pointer.

当您尝试访问悬空指针(即指向已释放的对象的指针)或未初始化的指针时,可能会发生这种情况。

The error is not in the code you posted, but rather in the code that produces the _direction argument to that method.

错误不在您发布的代码中,而是在为该方法生成_direction参数的代码中。

#1


3  

Objects live on the heap, what you are calling NSString is actually a pointer to it. And a pointer is a memory address, so that's expected behavior not a issue.

对象存在于堆上,你所谓的NSString实际上是指向它的指针。指针是一个内存地址,因此预期的行为不是问题。

EXC_BAD_ACCESS means that you are accessing the memory in a bad way, i.e. the memory address you are pointing to is not valid memory.

EXC_BAD_ACCESS表示您正在以错误的方式访问内存,即您指向的内存地址不是有效内存。

This can happen when you try to access a dangling pointer (i.e. a pointer to an object that was already released) or an uninitialized pointer.

当您尝试访问悬空指针(即指向已释放的对象的指针)或未初始化的指针时,可能会发生这种情况。

The error is not in the code you posted, but rather in the code that produces the _direction argument to that method.

错误不在您发布的代码中,而是在为该方法生成_direction参数的代码中。