繁体   English   中英

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

[英]Trying to access property from another class 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.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
}

Class1.m

- (void)updateTimeLabel {

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

所以我的问题是,可能出什么问题了?

UPDATE Class2.m

- (void)completeTransaction:(SKPaymentTransaction *)transaction {
    NSLog(@"completeTransaction...");

    [self provideContentForProductIdentifier:transaction.payment.productIdentifier];
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

    //initialize the timer and start it
    cls1 = [[Class1 alloc] init];
    self.timerCount = 0;
    timer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(timerIncrement) userInfo:nil repeats:YES];
    [timer fire];
}

- (void)timerIncrement {
    self.timerCount = self.timerCount-1;

    [cls1 updateTimeLeftLabel];

    NSLog(@"%@", [NSString stringWithFormat:@"IAP: %i", self.timerCount]);
}

Class1.m

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

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

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

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

仅创建单个实例并使用它。

暂无
暂无

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

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