【发布时间】:2011-12-05 15:57:14
【问题描述】:
我正在尝试在我的 iPhone 项目的两个视图之间共享一个字符串。如果我使用实际的@"something here" 作为字符串,它目前可以工作,但如果我想使用 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 下。 如果您将 locationField.text 替换为字符串 (@"blahblahblah"),它不会崩溃并且可以正常工作。
当它崩溃时,我收到错误:程序收到信号:“SIGABRT”
编辑:我尝试改变
initWithString:locationField.text
到
initWithFormat:@"%@",locationField.text
现在我在第二个视图中的标签打印“(NULL)”
感谢您抽出宝贵时间提供建议,非常感谢。
【问题讨论】:
-
尝试声明 locationString。
-
我尝试将它作为 ivar 添加到 Info_ViewController.h,但它没有改变任何东西。你的意思是让我在别处声明吗?
标签: iphone objective-c xcode4 ios5 singleton