简体   繁体   English

分配NSInteger *

[英]Allocate NSInteger*

I'm sure I'm missing something obvious but I'd like to create an instance of a NSInteger pointer in Objective C. 我确定我缺少明显的东西,但是我想在目标C中创建一个NSInteger指针的实例。

-(NSInteger*) getIntegerPointer{
  NSInteger  refValue = 0;
  NSInteger* theReturn = &refValue;
  return theReturn;
}

When I call this function theReturn is nil, but is valid within the function with the debugger. 当我调用此函数时, theReturn为零,但在调试器的函数中有效。

Any suggestions? 有什么建议么? I do not want to change theReturn to NSInteger. 我不想将theReturn更改为NSInteger。

The variable refValue is a local variable, which means that it will be on the stack while the -getIntegerPointer method is executing. 变量refValue是一个局部变量,这意味着它在执行-getIntegerPointer方法时将位于堆栈中。 As soon as that method returns, the variable will go away (be popped off the stack), so it's address is no longer meaningful. 该方法返回后,变量将消失(从堆栈中弹出),因此其地址不再有意义。

If you want to return a valid pointer, you have to allocate the memory for the thing being pointed to, like this: 如果要返回有效的指针,则必须为要指向的对象分配内存,如下所示:

-(NSInteger*) getIntegerPointer{
    NSInteger  refValue = 0;
    NSInteger* theReturn = malloc (sizeof(NSInteger));
    *theReturn = refValue;
    return theReturn;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM