什么是Setter和Getters

什么是Setter和Getters

本文介绍了什么是Setter和Getters?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Objective-C的Setters和Getters并没有真正的了解.有人可以为初学者提供良好的指导吗?我注意到这在尝试访问另一个类中的变量时会起作用,我现在正在尝试这样做.我有两个类,可以说A和B.我在A中有一个NSString变量,它带有@property(保留)NSString *变量.然后,我继续进行合成.现在,当视图加载到类中时,我将变量的值设置为"hello".现在,我要做的就是访问类B中的字符串.我已经导入了类A,并使用以下代码对其进行了初始化:

I don't really have a solid understanding of Setters and Getters for objective-c. Can someone provide a good guide for beginners? I noticed that this comes into play when trying to access variables in another class, which I am trying to do right now. I have two classes, lets say A and B. I have a NSString variable in A with the @property (retain) NSString *variable. Then I go ahead and synthesize it. Now when the view loads in the class I set the value for the variable to "hello". Now what I want to do is access the string from class B. I have imported the the class A, and initialized it with this code:

AClass *class = [[AClass alloc] init];
NSLog(@"Value:%@", class.variable);
[class release];

但是在调试器中,它返回的值(null)",我不太了解.如果有人可以带领我走上正确的道路,我将不胜感激.

However in the debugger it returns a value of "(null)", which I don't really understand. If someone could lead me into the right path I would greatly appreciate it.

谢谢

凯文

推荐答案

您感兴趣的特定部分是声明的属性.

The particular section of interest to you is Declared Properties.

b的界面应如下所示:

b's interface should look like:

@interface b : NSObject {
    NSString *value;
}

@property (nonatomic, retain) NSString *value;

- (id) initWithValue:(NSString *)newValue;

@end

您对b的实现应类似于:

Your implementation of b should look something like:

@implementation b

@synthesize value;

- (id) initWithValue:(NSString *)newValue {
    if (self != [super init])
        return nil;

    self.value = newValue;

    return self;
}

@end

然后您可以拨打以下电话:

Which you could then call like:

b *test = [[b alloc] initWithValue:@"Test!"];
NSLog(@"%@", test.value);

这篇关于什么是Setter和Getters?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 19:33