基本目标C变量声明 [英] Basic objective C variable declaration

查看:80
本文介绍了基本目标C变量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在目标C中如何声明变量感到困惑.

I am puzzled by how is variable declared in objective C.

1:我看到正在使用 @property @synthesize 语句.我的问题是,这两个语句是做什么用的?为什么它们总是一起使用?我想 @synthesize 是创建getter和setter的快捷方式?

1: I see @property and @synthesize statement being used. My question regarding that is, what are these 2 statement for? Why are they always used together? I guess @synthesize is a shortcut to create the getter and setter?

2:说,我想声明一个NSMutableArray,该NSMutableArray仅可在声明了该类的类内访问.我必须执行 myArray = [[[NSMutableArray alloc] init] ,然后再使用 addObject 方法向其中写入内容.那我什么时候释放阵列呢?

2:Say, I want to declare an NSMutableArray that would be only be accessible inside the class that was declared in. I have to perform myArray = [[NSMutableArray alloc] init] before using the addObject method to write something to it. When do I release the array then?

3:是否有另一种方法来声明仅在声明为所有类都可以访问的类中才可访问的变量?

3:Is there a different way to declaring a variable that is only accessible only at the class it was declared to being accessible at all classes?

4:类似于问题2,但是现在变量是一个NSString.为什么我不必分配&初始化它以在其自己的类中共享相同的变量吗? self.myString = @"; myString = @";

4:Similar to question 2, but now the variable is an NSString. Why I don't have to alloc & init it to share the same variable within its own class? Whats the different between self.myString = @""; to myString = @"";

非常感谢.

推荐答案

第一个问题:

@property (nonatomic, retain) NSString * someProperty;

这声明了该类的一个属性.它成为该类公共合同的一部分,但仍然缺少一些重要内容-实际实现

This declares a property of the class. It becomes part of the public contract of the class but still lacks something important - actual implementation

@synthesize someProperty;

这是编译器糖,它为您的属性创建一个getter和setter方法.总而言之,这是为了在您的类和其他类中实际使用您的属性所必需的实现.

This is compiler sugar, its creates a getter and setter method for your property. To wit, this is the implementation that is needed in order to actually use your property in your class and from other classes.

在几乎所有情况下,您声明的每个 @property 始终都有一个 @synthesize .

You will in almost all situations, always have a @synthesize for each @property you declare.

第二个问题:

您对如何初始化数组属性是正确的.为了释放它,您可以在类的dealloc方法中执行以下操作:

You are correct about how to initialize your array property. In order to release it you would do the following in your classes dealloc method:

- (void) dealloc {
    self.myarray = nil;

    [super dealloc];
}

这有效地释放了数组(假设您使用关键字 retain 声明了属性).

This effectively releases the array (assuming you declared your property with the keyword retain).

最后一个问题:

一个类的属性始终可以从其他类中获得.为了创建可全局访问的变量,您可以将其声明为 static .

Properties of a class are always available from other classes. In order to create a globally accessible variable you would declare it as static.

这篇关于基本目标C变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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