Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 试图从另一个类Objective-c访问属性_Ios_Objective C - Fatal编程技术网

Ios 试图从另一个类Objective-c访问属性

Ios 试图从另一个类Objective-c访问属性,ios,objective-c,Ios,Objective C,我有两个类,Class1(UIViewController)和Class2(NSObject)。在Class2中,我有一个属性,timerCount,每4秒增加1。我想将该值设置为Class1中的标签,但它只返回0。但是它直接在Class2中返回正确的值 Class2.h @property (nonatomic) int timerCount; Class2.m @synthesize timerCount; - (void)timerStart { self.timerCoun

我有两个类,Class1(UIViewController)和Class2(NSObject)。在Class2中,我有一个属性,timerCount,每4秒增加1。我想将该值设置为Class1中的标签,但它只返回0。但是它直接在Class2中返回正确的值

Class2.h

@property (nonatomic) int timerCount;
Class2.m

@synthesize timerCount;

- (void)timerStart {

    self.timerCount = 0;
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(timerIncrement) userInfo:nil repeats:YES];
    [timer fire];
}

- (void)timerIncrement {

    self.timerCount = self.timerCount+1;

    Class1 *cls1 = [[Class1 alloc] init];
    [cls1 updateTimeLabel];
    NSLog(@"%@", [NSString stringWithFormat:@"%i", self.timerCount]); //logs correct numbers
}
- (void)updateTimeLabel {

    Class2 *cls2 = [[Class2 alloc] init];
    NSLog(@"%@", [NSString stringWithFormat:@"%i", cls2.timerCount]);  //logs 0 every 4 second
}
Class1.m

@synthesize timerCount;

- (void)timerStart {

    self.timerCount = 0;
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(timerIncrement) userInfo:nil repeats:YES];
    [timer fire];
}

- (void)timerIncrement {

    self.timerCount = self.timerCount+1;

    Class1 *cls1 = [[Class1 alloc] init];
    [cls1 updateTimeLabel];
    NSLog(@"%@", [NSString stringWithFormat:@"%i", self.timerCount]); //logs correct numbers
}
- (void)updateTimeLabel {

    Class2 *cls2 = [[Class2 alloc] init];
    NSLog(@"%@", [NSString stringWithFormat:@"%i", cls2.timerCount]);  //logs 0 every 4 second
}
所以我的问题是,会出什么问题

更新 类别2.m

1.m班

- (void)viewDidLoad {
    cls2 = [[Class2 alloc] init];
}

- (void)updateTimeLeftLabel
{
    NSLog([NSString stringWithFormat:@"%i", cls2.timerCount]);    
}

您正在
updateTimeLabel
方法中创建一个新的、临时的Class2对象。您应该引用运行计时器的原始Class2对象。

您不应该每次创建新实例。这是您收到0的唯一原因。因为每个新实例都指向新地址


只创建一个实例并使用它。

如何引用该对象@Guy Kogusook,那你怎么做呢?
Class1
应该有一个类型为
Class2
的属性,它可以引用。就像您有属性
timerCount
,添加另一个属性:
@property(非原子,强)Class2 cls2我只是在viewDidLoad中初始化了每个类的两个实例,这样它们只创建一次。你也应该只初始化一次到Class2。好的,不,它无论如何都不起作用。可能是上面的答案吗?你能回答我对这个答案的评论吗