Reputation: 96391
if header file declares
@interface SomeClass: NSObject {
Data* d;
}
@property (nonatomic, retain) Data* d;
Why is the following line in the implementation file giving me a warning (and init
method does not get called?)
[[[self d] alloc] init];
The warning i get is
Instance method '-alloc' not found (return type defaults to 'id')
Meanwhile, Data
has
- (id) init
method, that is not being called.
Please help me understand why.
Upvotes: 0
Views: 1261
Reputation: 28806
alloc
should be invoked on a class, not on an instance.
interface SomeClass : NSObject
{
Data *d;
}
Declare an init method on SomeClass and make it look like:
- (id) init
{
self = [super init];
if (self)
{
d = [[Data alloc] init];
}
return self;
}
- (void) dealloc
{
[d release];
[super dealloc];
}
Now you do:
SomeClass *c = [[SomeClass init] alloc];
And you can use the class. Note that you should probably read a little more on classes and objects and about memory management too (when you should release c, etc.).
If, by any chance, you have the possibility to use ARC (automatic reference counting), you won't need to take care of releasing stuff. But that doesn't come with Xcode 4.1, only with 4.2 which is not publicly accessible, apparently.
Upvotes: 5
Reputation: 956
You should be doing
self.d = [[Data alloc] init];
As Matt says, alloc
is a class method, and must be called on the class itself.
Upvotes: 1
Reputation: 20153
The problem isn't -(id)init
, it's -(id)alloc
. alloc is a class method of NSObject, which means you send it to the class itself and not to an instance of that class, i.e.:
[Data alloc]; // Correct
[someDataInstance alloc]; // Method not found
When you call [self d]
, you're given an instance of a Data, which you're then sending a -(id)alloc message to. Since NSObject doesn't have a -(id)alloc
(only a +(id)alloc
), you get the warning.
Upvotes: 2