I have Class1, Class2, and SubclassOfClass2. I want to call method that is in SubclassOfClass2 from Class1. I do:
Class2 *class = [[Class2 alloc] init];
[class someMethod];
But, as I guess, due to alloc, all variables values are being lost after that. Because:
At runtime Class2 is being executed. It sets for example variable float x = image.size.width. And it returns correct value. Later, after for example user pressed button, Class1 is being executed. After calling someMethod from Class1 variable x returns 0.00000. How to make it working so that variables values wouldn’t be lost?
As I have been asked, here is my someMethod code:
-(void)someMethod {
NSLog(@"%f", x);
}
At run time that method returns 3200.00000 and when its called from Class1 it returns 0.00000. Variable x is declared in Class2 and method someMethod is in SubclassOfClass2
Class1.h
@interface Class1
@end
Class1.m
#import "Class1.h"
#import "Class2.h"
@implementation Class1
-(IBAction)buttonPressed:(id)sender {
Class2 *class = [[Class2 alloc] init];
[class someMethod];
}
@end
Class2.h
@interface Class2 {
float x;
}
@end
Class2.m
#import "Class2.h"
#import "SubclassOfClass2.h"
@implementation Class2
- (id)initWithCoder:(NSCoder *)coder {
x = 3200;
[self someMethod];
return self;
}
@end
SubclassOfClass2.h
#import "Class2.h"
@interface Class2 (subclass) {
}
-(void)someMethod;
@end
SubclassOfClass2.m
#import "SubclassOfClass2.h"
@implementation Class2 (subclass)
-(void)someMethod {
NSLog(@"%f", x);
}
@end
It returns 0.00000 because you’re calling
init. That’s a different method frominitWithCoder:, which is the one that setsx.(Other problems: have your classes inherit from NSObject as a base class and don’t use
classas a variable name…especially when it’s not a class object.)