Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c main()之外的变量值不正确_Objective C_Cocoa - Fatal编程技术网

Objective c main()之外的变量值不正确

Objective c main()之外的变量值不正确,objective-c,cocoa,Objective C,Cocoa,我有这个密码 #import <Foundation/Foundation.h> int testint; NSString *teststring; int Test() { NSLog(@"%d",testint); NSLog(@"%@",teststring); } int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool a

我有这个密码

#import <Foundation/Foundation.h>
int testint;
NSString *teststring;

int Test()
{
    NSLog(@"%d",testint);
    NSLog(@"%@",teststring);
}


int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    testint = 5;
    NSString *teststring = [[NSString alloc] initWithString:@"test string"];
    Test();
    [pool drain];
    return 0;
}
#导入
智力测验;
NSString*teststring;
int测试()
{
NSLog(@“%d”,测试);
NSLog(@“%@”,teststring);
}
int main(int argc,const char*argv[]{
NSAutoreleasePool*池=[[NSAutoreleasePool alloc]init];
testint=5;
NSString*teststring=[[NSString alloc]initWithString:@“测试字符串”];
Test();
[泳池排水沟];
返回0;
}
在输出中,我有:

5 (null)
五, (空)


为什么测试函数看不到正确的测试字符串值?要在输出中有正确的“测试字符串”,我应该怎么做?

您有两个不同的变量名为
testint
main()
中的一个隐藏了全局变量。

您正在用局部变量隐藏全局变量。如果目的是使用全局testString,则不应使用“NSString*”重新声明它

在输出中,我有:

5 (null)
为什么测试函数看不到正确的测试字符串值

因为你从来没有分配过任何东西。在
main
中,您使用相同的名称声明了一个局部变量,并使用指向您创建的NSString对象的指针初始化了该变量


如何使用“alloc init”声明全局对象

你没有

声明创建变量(有时是类型)。
NSString*teststring
行(两行)都是声明:一个是全局变量,另一个是局部变量

alloc
消息(以及类的大多数其他消息)创建对象

因此,这一行:

NSString *teststring = [[NSString alloc] initWithString:@"test string"];
声明了一个局部变量(
teststring
)并创建了一个string对象,并初始化了该变量以保存指向string对象的指针

(请注意,“
initWithString:
”初始化对象,而不是变量。从
=
到分号的部分是变量的初始化器。)

您的意思是分配给全局变量,而不是声明局部变量。这样做:省去类型说明符,将声明转换为赋值语句:

teststring = [[NSString alloc] initWithString:@"test string"];
顺便说一下,您不需要在这里使用
alloc
initWithString:
<代码>@“测试字符串”已经是NSString对象。当您执行alloc时,不要忘记释放它(假设您没有打开GC)


如何使用“alloc init”声明全局对象

字符串是一种特殊情况。您可以这样做:

NSString* foo = @"bar";

我应该如何用“alloc init”声明全局对象?可能在专用的初始化函数或main中。只要去掉类型,它就会变成赋值而不是声明。您也可以考虑不使用全局变量,并将数据传递给需要它们的函数。