单例,公共或全局变量使用

时间:2012-04-02 19:34:26

标签: iphone global-variables

我已经搜索并尝试了关于此主题的堆栈溢出中的单例,公共和全局变量的每个示例。我在哪里弄错了。我有一个名为strIP的设置变量,它是textField的一部分,在我的secondViewController.h中声明。我希望在名为myWSupdate.m的类中使用此变量。它只是一个变量,我想将它传递给连接字符串。这个编译正确,但应用程序在运行时崩溃。我做错了什么?

来自编译器的

错误:由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'+ [SecondViewController sharedIP]:无法识别的选择器发送到类0x6403c'

secondViewController.h

@interface SecondViewController : UIViewController
{
UITextField *ipAdd;

NSString *strIP;

}
@property (nonatomic, retain) IBOutlet UITextField *ipAdd;
@property (retain) NSString  *strIP;

+(SecondViewController*)sharedIP;

然后我在myWSupdate.m中调用它:

#import "SecondViewController.h"

/* Implementation of the service */

@implementation myWSupdate

- (id) init
{
    if(self = [super init])
    {

        SecondViewController* IP = [[SecondViewController sharedIP]init];
NSLog(@"the test has %@", IP.strIP);
    }
}


@end

1 个答案:

答案 0 :(得分:2)

由于strIP属于SecondViewController,因此您需要将其作为该对象的一部分进行引用。

如何做到这一点取决于SecondViewControllermyWSupdate之间的关系。 (例如,如果控制器创建了一个myWSupdate对象,则可以将该变量作为init的一部分传递。)

它被标记为公开的事实并没有改变它是实例变量的事实,因此需要与其类的实例结合使用。< / p>