简体   繁体   English

从另一个Objective-C类访问int

[英]Access int from Another Objective-C Class

I've trying to get an int from another class and it just says that the number is 0 (but it's not). 我试图从另一个类中获取一个int,它只是说数字是0(但不是)。

This is in Class2.h: 这是在Class2.h中:

@interface Class2 : SKScene <SKPhysicsContactDelegate>{
    Class1 * class;
}

This is in Class2.m: 这是在Class2.m中:

NSLog(@"%i", class.thisint);

This is in Class1.h: 这是在Class1.h中:

@property (assign, nonatomic) int thisint;

This is in Class1.m (in viewDidLoad): 这是在Class1.m中(在viewDidLoad中):

thisint = 5;

The NSLog is being called well after the viewDidLoad method but it just keeps saying 0. How do I get this int from Class1? NSLog在viewDidLoad方法之后被很好地调用,但是它一直说0。如何从Class1获得此int? I don't know if the fact that Class2 is an SKScene affects this... 我不知道Class2是SKScene的事实是否会影响这一点...

class is an existing method on NSObject and I would hope that you've just used that name for the purposes of this question - if not, please change the name of the variable, it will only lead to confusion. class是NSObject上的现有方法,我希望您只是出于该问题的目的使用了该名称-如果没有,请更改变量的名称,这只会导致混乱。

What do you see if you log class : 如果您登录class会看到什么:

NSLog(@"%@",class);

(Put that next to where your existing log is) (将其放在您现有日志的旁边)

How and where are you assigning to the class variable? 您如何以及在何处分配给class变量?

A value of 0 probably means one of two things: 值为0可能意味着以下两种情况之一:

  • class is nil . class nil This means you haven't assigned it anywhere. 这意味着您尚未在任何地方分配它。 You don't magically get a value in a property just because you've declared one 您不能仅仅因为已经声明了一个而神奇地获得属性的值
  • class is a different instance to the one you think it is. class与您认为的是不同的实例。 This is a common beginner mistake, where you've done something like 这是一个常见的初学者错误,您在其中做了类似的事情

     class = [[Class2 alloc] init]; 

Which creates a new instance. 这将创建一个实例。 You need to get a reference to the existing instance, which I can't tell you how to do without seeing more code. 您需要获得对现有实例的引用,在看不到更多代码的情况下我无法告诉您该怎么做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM