简体   繁体   中英

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. 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 ?

Like this in the .h interface:

@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:

@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.

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).

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.

In interface (.h) use ONE of these, NOT all of them:

@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):

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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