在视图之间使用单例共享数据/字符串

时间:2011-12-05 15:57:15

标签: iphone objective-c xcode4 ios5 singleton

我正在尝试在我的iPhone项目中的两个视图之间共享一个字符串。它现在可以工作,如果我使用实际的@“这里的东西”的字符串,但如果我想使用像label.text这样的东西,它甚至不是它仍然是一个字符串。

我会告诉你我需要做些什么来使它更清楚。

第一视图:Info_ViewController.h

#import <UIKit/UIKit.h>

@interface Info_ViewController : UIViewController {

    IBOutlet UITextField *locationField;

}

@property (nonatomic, retain) NSString *locationString;

+ (id)sharedInfoVC;

@end

第一个视图:Info_ViewController.m

#import "Info_ViewController.h"

static Info_ViewController *sharedInfoVC = nil;

@implementation Info_ViewController
@synthesize locationString;


#pragma mark Singleton Methods
+ (id)sharedInfoVC {
    @synchronized(self) {
        if (sharedInfoVC == nil)
            sharedInfoVC = [[self alloc] init];
        }
    return sharedInfoVC;
}

- (id)init {
    if (self = [super init]) {
        locationString = [[NSString alloc] initWithString:locationField.text]; //This is there part I mentioned earlier, when using @"something" instead of locationField.text works.
    }
    return self;
}

第二个视图:Confirm_ViewController.m

#import "Confirm_ViewController.h"
#import "Info_ViewController.h"

@implementation Confirm_ViewController

- (IBAction)buttonZ:(id)sender
{
    Info_ViewController *infoVCmanager = [Info_ViewController sharedInfoVC];
    locationLabel.text = infoVCmanager.locationString;
}

我现在把它放在一个按钮下,但最终会在viewDidLoad下。 如果用一个字符串(@“blahblahblah”)替换locationField.text,它将不会崩溃并起作用。

当它崩溃时我收到错误:程序收到信号:“SIGABRT”

编辑:我尝试过更改

initWithString:locationField.text

initWithFormat:@"%@",locationField.text

现在我在第二个视图中的标签打印“(NULL)”

感谢您抽出宝贵时间提供建议,我真的很感激。

3 个答案:

答案 0 :(得分:1)

将nil作为格式字符串传递给 - [NSString initWithString]是错误的。

那你怎么通过零呢?实际上你有两个的Info_ViewController实例。你有一个实例,它是你的应用程序的正常部分,然后你还有一个第二个实例,它是你的“单身人士”(它实际上不再是单身人士)。

所以在你的“singleton”实例中,UITextField是nil(并且将始终为nil),因此locationField.text为nil,你将它传递给initWithString:,这是一个崩溃。事实上,“单身人士”甚至没有像观察控制者那样完全烘焙。

如果您希望单例在应用程序的其他位置共享数据,那么它实际上不应该是Info_ViewController或任何类型的视图控制器。它应该是您用来管理数据的其他类。我会创建另一个类并将其实现为单例。

希望能帮助您了解这里发生的事情。

答案 1 :(得分:0)

预先“自我”。到您的位置字符串。

    self.locationString = [[NSString alloc] initWithString:locationField.text]; 

答案 2 :(得分:0)

根据我对您的代码的理解,当您初始化viewController时,您从textfield获得了locationString的值。此时,您的文本字段将不可见。在它变得可见并输入内容之后,您没有将代码存储到locationString。

您应该做的是等待Info_ViewController对象初始化和显示。然后在按下某个按钮或其他事件时,从locationString分配locationLabel.text,甚至直接从locationField.text分配。

我会提供代码,但我不知道你是如何构建它的。如果您仍需要帮助,请提供详细信息。

相关问题