Answer the question
In order to leave comments, you need to log in
How to access a variable from another class?
How to access 'pew' variable from another class (ViewController)?
// ImageTouched.h
#import <UIKit/UIKit.h>
@interface ImageTouched : UIImageView
@property (nonatomic, strong) NSString *pew;
@end
#import "ImageTouched.h"
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"Image Touched");
self.pew = @"pewpewpewew";
}
#import "ImageTouched.h"
- (void)viewDidLoad
{
[super viewDidLoad];
ImageTouched *instance = [[ImageTouched alloc] init];
NSLog(@"Pew value is %@", instance.pew);
}
log:Pew value is (null)
Image Touched
Answer the question
In order to leave comments, you need to log in
I think the problem is that the 'pew' variable is initialized after clicking on the picture. At this point myViewController is already loaded. We need a method that would handle events after the controller is loaded.
what what? I don’t understand the meaning, describe in more detail
such code will initialize pew before NSLog is executed#import "ImageTouched.h" -(void)awakeFromNib { self.pew = @"pewpewpewew"; }
I think the problem is that the 'pew' variable is initialized after clicking on the picture. At this point myViewController is already loaded. We need a method that would handle events after the controller is loaded.
In the viewcontroller's code, write
- (void)viewDidLoad {
[super viewDidLoad];
ImageTouched *instance = [[ImageTouched alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[self.view addSubview:instance];
// Подписываемся на уведомление
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageDidTouch:) name:@"ImageTouchedImageDidTouch" object:nil];
}
// Метод, который обрабатывает уведомление
- (void)imageDidTouch:(NSNotification *)notification {
if ([notification.object isKindOfClass:[ImageTouched Class]])
NSLog(@"Pew value is %@", ((ImageTouched *)notification.object).pew);
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"Image Touched");
self.pew = @"pewpewpewew";
// Отправить уведомление, отправляя самого себя в качестве параметра object
[[NSNotificationCenter defaultCenter] postNotificationName:@"ImageTouchedImageDidTouch" object:self];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question