【发布时间】:2013-11-01 17:00:37
【问题描述】:
我有两个 ViewController。
FirstViewController 有 UILabels 和 UIImageViews。还从其类中生成了一个 Singleton。 SecondViewController 调用了那个 Singleton,应该从 FirstViewController 获取 UILabels 和 UIImageViews 的值。
NSString 有效,UILabel 无效。
例如,使用“sharedFirstViewController.nsstringvarname”访问 SecondviewController 中的 NSString,我可以 GET 和 SET 值。 这很好用!
尝试使用类似这样的 UILabel:“sharedFirstViewController.uilabelvar.text” 我无法设置或获取此 UILable 的值。 这行不通!
UI-Objects 有什么特别之处吗? 如果有人可以帮助我,那就太好了。 谢谢!
编辑:
在 FirstViewController.h 中
+ (id)sharedFirstViewController;
@property (copy, nonatomic) NSString *path;
@property (strong, nonatomic) IBOutlet UIImageView *pic;
在 FirstViewController.m 中
@synthesize path= _path;
@synthesize pic = _pic;
- (id)init {
if (self = [super init]) {
_pic = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 200)];
}
return self;
}
+ (id) sharedFirstViewController {
static sharedFirstViewController * sharedFirstViewController = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedFirstViewController = [[self alloc] init];
});
return sharedFirstViewController;
}
在 SecondViewController.m 中
#import "FirstViewController.h"
- (void)viewDidLoad
{
FirstViewController * sharedFirstViewController = [FirstViewController sharedFirstViewController];
NSLog(@"this is NSString from FVC: %@" sharedFirstViewController.path); //works
UIImage * picture = [UIImage imageWithContentsOfFile:sharedFirstViewController.path];
sharedFirstViewController.pic.image = picture; // does´t work
}
【问题讨论】:
-
代码和具体错误将有助于找出问题所在
-
向您展示如何制作单例类及其变量的代码
标签: objective-c nsstring singleton uilabel