Reputation: 21019
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;
}
Upvotes: 3
Views: 200
Reputation: 3401
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];
}
Upvotes: 1
Reputation: 4094
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.
Upvotes: 0
Reputation: 46027
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
Upvotes: 5
Reputation: 3752
You do need to implement dealloc, and release all of your ivars. Also, don't forget to @synthesize your properties!
Upvotes: 0
Reputation: 86651
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
Upvotes: 1
Reputation: 2677
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.
Upvotes: 3