为什么某些对象成员超出了目标C的范围 [英] Why are some object members out of scope in Objective C

查看:88
本文介绍了为什么某些对象成员超出了目标C的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从Java背景来学习Objective-C的.我无法理解以下代码为何生成异常.

I'm coming to Objective-C from a Java background. I'm having trouble understanding why the following code generates an exception.

    
@interface Stopwatch : NSObject {
    NSDate *start;
    int    mode;
}
@property(nonatomic,assign) NSDate *start;
@property(nonatomic,assign) int mode;
@end

@implementation Stopwatch
@synthesize start, mode;
-(id) init{
    self = [super init];
    if(self){
        start = [NSDate date];
        mode = -1;
    }
    return self;
}
@end


@interface StopwatchController : NSObject {
    Stopwatch *stopwatch;
}
@property (nonatomic,assign) Stopwatch *stopwatch;

- (void) useStopwatch:(Stopwatch*)aStopwatch;
- (void) updateStopwatch;
@end

@implementation StopwatchController
@synthesize stopwatch;

- (void) useStopwatch:(Stopwatch*)aStopwatch{
    stopwatch = aStopwatch;
}

- (void) updateStopwatch{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setTimeStyle:NSDateFormatterMediumStyle];
    [dateFormat setDateStyle:NSDateFormatterMediumStyle];
    NSString *string = [dateFormat stringFromDate:stopwatch.start];
    NSLog(@"%@",string);
}
@end

因此,当运行以下代码时,我发现秒表.start不在范围内,但秒表不在范围内?

So when the following code is run I see that the stopwatch.start is out of scope, but not the stopwatch?


Stopwatch *sw = [[Stopwatch alloc]init];
StopwatchControlelr *swc = [[StopwatchController alloc]init];
[swc useStopwatch:sw];
[swc updateStopwatch];

推荐答案

在您的init中

start = [NSDate date];

不使用start属性-它使用start实例变量.这意味着从未调用过保留. [NSDate date]返回一个将自动释放的对象.

Does not use the start property -- it uses the start instance variable. This means that a retain was never called. [NSDate date] returns an object that will autorelease.

我的建议是使用

self.start = [NSDate date];

这将使用该属性.在您的情况下,我还要声明此属性retain,而不是assign.如果将其保留为assign,则需要调用保留".因此,对于assign,也可以这样做

This uses the property. In your case, I would also declare this property retain, not assign. If you keep it assign, you need to call retain. So with assign, also do this

[self.start retain];

确保正确执行操作的一种方法是声明这样的字段

One way to make sure you do it right is to declare fields like this

NSDate * _start;

像这样的财产

@property (retain, nonatomic) NSDate * start;

然后像这样合成

@synthesize start = _start.

然后,您知道何时使用实例变量(绕过任何设置调用,自动保留等)或属性.

Then you know when you are using the instance variable (which bypasses any set calls, automatic retains, etc) or the property.

如果您这样做,那么它将无法编译

If you did that, then this would not compile

   start = [NSDate date];

您要么需要对此进行更改

You'd either need to change to this

   self.start = [NSDate date]; // use property

或这个

   _start = [NSDate date]; // use instance variable

这篇关于为什么某些对象成员超出了目标C的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆