开发者

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


I may be wrong, and I'm sure someone will correct me ;), but if you're not doing any special initializations, you don't need the init method.


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 @synthesizeing 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 do need to implement dealloc, and release all of your ivars. Also, don't forget to @synthesize your properties!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜