Passing a pointer to a function in objective-c
i've a stupid questiona about passing pointer.
I've this:
@interface MyClass : NSObject
myobj* foo;
-(void)doSomething:(myobj*)aObj;
@end
@implementation MyClass
-(void)doSomething:(myobj*)aObj
{
cFuncCall(&aObj); //alloc memory and init开发者_C百科 the object
}
-(id)init
{
//init stuff...
[self doSomething:foo]; // foo retun 0x0!!!
}
@end
why foo return nil??? It should be initialized by cFuncCall! [update]
Yes the problem is that foo is not changin outside doSomething. I've tried with myobj** but foo is still nil... This is the real code:
I declare FMOD::DSP *lowpassDSP;
in the class interface. No property is set.
This is the function that sould init lowpassDSP.
-(void)configFilter:(FMOD::DSP**)dsp
{
system->createDSPByType(FMOD_DSP_TYPE_LOWPASS, dsp);
baseChannel->addDSP(*dsp, 0);
}
and this is the call:
[self configFilter:&lowpassDSP];
in configFilter the dsp variable is correctly initiated but lowpassDSP is nil after calling configFilter.
The problem is that your object variable foo
is not changed outside of doSomething:
.
Try the following:
-(void)doSomething:(myobj**)aObjP
{
cFuncCall(aObjP);
}
-(id)init
{
//...
[self doSomething:&foo];
}
First of all your -init method isn't defined correctly, perhaps this causes the problem (the superclass of your class isn't properly initialized). Your -init methods should be defined like this in objC:
- (id)init {
if (self = [super init]) {
// do custom initialization here, perhaps [self doSomething:foo] if required ...
}
return self;
}
-Edit:
Well, in objective-C I've often seen pointers passed to objects like this (notice the pointer-to-pointer notation), I'm not sure if this will work fine in ANSI C as well for passing pointers to methods, but you could check it out:
- (void)callFunction {
NSError *error = nil;
[self doSomethingWithError:&error];
if (error != nil) {
NSLog(@"error: %@", error];
}
}
- (void)doSomethingWithError:(NSError **)error {
// do something ...
}
精彩评论