简体   繁体   中英

Creating an Object - Objective-C

Problem

I am trying to create an object in Objective-C. I know how to do it but I have a few questions regarding the methods in the implementation file.

The Object:

@interface Program : NSObject {
    NSString *sid;
    NSString *le;
    NSString *sd;
    NSString *pid;
    NSString *n;
    NSString *d;
    NSString *url;
}

@property (nonatomic, retain) NSString *sid;
@property (nonatomic, retain) NSString *le;
@property (nonatomic, retain) NSString *sd;
@property (nonatomic, retain) NSString *pid;
@property (nonatomic, retain) NSString *n;
@property (nonatomic, retain) NSString *d;
@property (nonatomic, retain) NSString *url;

@end

Question

I should only implement dealloc and init .. Am I right on this?

Furthermore, I have no special initializations, so should I keep the default init method as follows?

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }

    return self;
}

You need to synthesize the properties and if you don't need any custom initialization then you can keep the init method as it is. In fact there is no need to implement init here. But in dealloc you need to release the strings.

@implementation Program

@synthesize sid;
// ... synthesize others

- (void)dealloc {
    [sid release];
    // ... release others

    [super dealloc];
}

@end

我可能错了,我确信有人会纠正我;),但是如果你没有做任何特殊的初始化,你就不需要init方法。

I should only implement dealloc and init.. Am I right on this?

You need to also implement all those properties, but you can make the compiler do all the hard work by @synthesize ing them.

Each of the properties needs to be released in your -dealloc

if you are creating a properties ( you should synthesize so the compiler will automatically generate getter and setter methods for us), and if you are doing custom initialization then you need to remember self keyword

-(id)init{
  self.sid = @"SID" //Without the self object & the dot we are no longer sending 
                     //an object a message but directly accessing ivar named sid
 }

 - (void)dealloc {
     self.sid = nil;
     [super dealloc];
   }

You only need to implement - dealloc and - init if you have tear-down or setup to do. If you have none, you don't have to implement either because the defaults inherited from NSObject do the job.

You do need to implement dealloc, and release all of your ivars. Also, don't forget to @synthesize your properties!

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