简体   繁体   English

如何在Objective-C中合成对象指针?

[英]How are object pointers in objective-c synthesized?

I'm new to Objective-C and I have been working with simple programs, and I was wondering how you would synthesize an Objective-C object pointer. 我是Objective-C的新手,我一直在使用简单的程序,我想知道您将如何综合Objective-C对象指针。 So if I had a simple header file like so: 因此,如果我有一个简单的头文件,例如:

//
//  Rectangle.h
//  Program 8

#import <Foundation/Foundation.h>
#import "XYPoint.h"

@interface Rectangle : NSObject
{
     XYPoint *origin;
}

- (XYPoint *) origin; // getter
- (void) setOrigin: (XYPoint *)pt; // setter
@end

How do you synthesize the object pointer *origin with @property and @synthesize ? 如何将对象指针*origin@property@synthesize合成?

Like this in the .h interface: 在.h界面中如下所示:

@property (nonatomic, retain) XYPoint* origin;

Nonatomic is optional and can be removed, which would make the property thread-safe. 非原子性是可选的,可以删除,这将使属性成为线程安全的。 Retain means that the reference count will be incremented, Copy is an alternative to this which copies and increments the reference count, Assign is an alternative which is not very safe for use with objects and more intended for primitive types. 保留表示将增加引用计数,复制是复制并递增引用计数的替代方法,复制是对对象使用不是很安全且更适合原始类型的替代方法。

In the .m implementation: 在.m实现中:

@synthesize origin;

or 要么

@synthesize origin = _origin;

In case you were wondering what the _origin is doing, there is a great explanation of this in the answer to this question here. 如果您想知道_origin在做什么,在此问题的答案中对此有很好的解释

Don't forget to release your properties in dealloc (or viewDidUnload - obviously not in the class you are writing here, but if working with a view controller). 不要忘记在dealloc(或viewDidUnload-显然不是在此处编写的类中,但是如果使用视图控制器)中释放属性。

Properties are used to avoid boilerplate code to get and set variables. 使用属性可以避免样板代码获取和设置变量。 In your case above you would not declare the getters and setter in the header, instead declare a property for origin and synthesize that in your implementation-file. 在上述情况下,您不会在标头中声明getters和setter方法,而是为origin声明一个属性并将其综合在实现文件中。

In interface (.h) use ONE of these, NOT all of them: 在接口(.h)中使用其中之一,而不是全部使用:

@property (retain) XYPoint* origin; // will increment the retain count (strong)
@property (copy) XYPoint* origin; // will make your own copy with retain count 1 (strong)
@property (assign) XYPoint* origin; // will not increase the retain count (not strong)

In implementation (.m): 在执行中(.m):

@synthesize origin;

Depending on how you are going to use "origin", you may either retain it, copy it or only assign it (see above). 根据您将如何使用“来源”,您可以保留,复制或仅分配它(请参见上文)。

Depending on what OS and version you are targeting you may not need to declare the actual variable or synthesize it (if I'm not remembering wrong), the property itself is enough. 根据您所针对的操作系统和版本,您可能不需要声明实际变量或对其进行综合(如果我记错了),则属性本身就足够了。

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

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