I just want to know the code for making an image called profpic accessible to all other ViewControllers that I make or intend to make. I have read many posts on global variables, public variables, and other suggestions that have yet to work. If it helps, I am specifically using this to display an image from ViewControllerA as the background for ViewControllerB.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can use a singleton class and put the UIImage
on it. Set it in ViewControllerA
and get it in ViewControllerB
@interface MySingleton : NSObject
@property (nonatomic, strong) UIImage *myImage;
+ (MySingleton *)sharedInstance;
@end
@implementation MySingleton
#pragma mark Singleton Methods
+ (MySingleton *)sharedInstance {
static MySingleton *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (id)init {
if (self = [super init]) {
}
return self;
}
@end
To access myImage
// set myImage in ViewControllerA
MySingleton *mySingleton = [MySingleton sharedInstance];
mySingleton.myImage = [UIImage imageNamed:@"imageName"];
// get my image in ViewControllerB
MySingleton *mySingleton = [MySingleton sharedInstance];
myImageView.image = mySingleton.myImage;