为什么我的基础课没有工作?

时间:2013-02-17 18:51:44

标签: objective-c

这让我发疯了。我有一节课:

@interface qanda : NSObject

@property (nonatomic, copy) NSString *quote;
@property (nonatomic, copy) NSString *author;

@end

是的,我确实在另一个文件中合成了它们。

然后在我的Viewdidload文件中,我声明了一些对象。

- (void)viewDidLoad
{
    qanda *qanda1 = [[qanda alloc] init];
    qanda1.quote = @"All our dreams can come true – if we have the courage to pursue          them. ";
    qanda1.author = @"Walt Disney";
}

我的ViewDidLoad文件有一个简短的摘录。

然而,当我尝试访问此对象的字符串时,我收到错误,我不知道为什么。

self.quote.text = qanda.quote;`

(顺便提一句就是出口) 我得到的错误是:“使用未声明的标识符'qanda1';你的意思是'qanda'?

1 个答案:

答案 0 :(得分:1)

从我在此处看到的情况来看,qanda *qanda1仅限于viewDidLoad方法。该方法返回后,qanda1不再存在。

在视图控制器的头文件中,声明qanda1的属性。

@class Qanda;    
@interface MyViewController : UIViewController
    .
    .
    .
@property Qanda *qanda1;
@end

在实现文件“MyViewController.m”中:

#import "Qanda.h"

@implementation MyViewController
.
.
.
-(void)viewDidLoad {
    Qanda *qanda1 = [[Qanda alloc] init];
    qanda1.quote = @"All our dreams can come true – if we have the courage to pursue          them. ";
    qanda1.author = @"Walt Disney";
}

.
.
.
@end

这样,您可以在qanda1的整个生命周期内访问MyViewController。现在,您可以在调用self.quote.text = qanda1.quote;后的任何时间执行viewDidLoad

我建议您阅读变量范围(here is a good starting point on SO),以便全面了解此处发生的事情。

<强>更新

正如您对问题的评论中所提到的,遵循一些基本的命名约定可能有助于区分实例变量和类名。 (对于Objective C,但大多数语言都采用相同的(如果不是相似的模式)。

遵循惯例,您的“qanda”课程将如下所示:

@interface Qanda : NSObject

@property (nonatomic, copy) NSString *quote;
@property (nonatomic, copy) NSString *author;

@end
相关问题