从Objective-C中的其他类访问方法

时间:2022-10-08 19:03:42

I have Class1, Class2, and SubclassOfClass2. I want to call method that is in SubclassOfClass2 from Class1. I do:

我有Class1,Class2和SubclassOfClass2。我想从Class1调用SubclassOfClass2中的方法。我做:

Class2 *class = [[Class2 alloc] init];
[class someMethod];

But, as I guess, due to alloc, all variables values are being lost after that. Because:

但是,正如我猜测的那样,由于alloc,所有变量值都会在此之后丢失。因为:

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?

在运行时,正在执行Class2。它设置了例如变量float x = image.size.width。它返回正确的值。稍后,例如用户按下按钮后,正在执行Class1。从Class1变量调用someMethod后,x返回0.00000。如何让它工作,以便变量值不会丢失?

As I have been asked, here is my someMethod code:

正如我被问到的,这是我的someMethod代码:

-(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

在运行时,该方法返回3200.00000,当从Class1调用它时返回0.00000。变量x在Class2中声明,方法someMethod在SubclassOfClass2中声明


Class1.h

Class1.h

@interface Class1

@end

Class1.m

Class1.m

#import "Class1.h"
#import "Class2.h"

@implementation Class1
-(IBAction)buttonPressed:(id)sender {
Class2 *class = [[Class2 alloc] init];
[class someMethod];
}
@end

Class2.h

Class2.h

@interface Class2 {
 float x;
}
@end

Class2.m

Class2.m

#import "Class2.h"
#import "SubclassOfClass2.h"

@implementation Class2
- (id)initWithCoder:(NSCoder *)coder {
    x = 3200;
    [self someMethod];
    return self;
}
@end

SubclassOfClass2.h

SubclassOfClass2.h

#import "Class2.h"

@interface Class2 (subclass) {
}
-(void)someMethod;
@end

SubclassOfClass2.m

SubclassOfClass2.m

#import "SubclassOfClass2.h"
@implementation Class2 (subclass)
 -(void)someMethod {
   NSLog(@"%f", x);
 }
@end

1 个解决方案

#1


2  

It returns 0.00000 because you're calling init. That's a different method from initWithCoder:, which is the one that sets x.

它返回0.00000,因为你正在调用init。这是与initWithCoder:不同的方法,它是设置x的方法。

(Other problems: have your classes inherit from NSObject as a base class and don't use class as a variable name...especially when it's not a class object.)

(其他问题:让你的类继承自NSObject作为基类,不要使用类作为变量名...尤其是当它不是类对象时。)

#1


2  

It returns 0.00000 because you're calling init. That's a different method from initWithCoder:, which is the one that sets x.

它返回0.00000,因为你正在调用init。这是与initWithCoder:不同的方法,它是设置x的方法。

(Other problems: have your classes inherit from NSObject as a base class and don't use class as a variable name...especially when it's not a class object.)

(其他问题:让你的类继承自NSObject作为基类,不要使用类作为变量名...尤其是当它不是类对象时。)