views:

731

answers:

4

I would like to declare a pointer to a pointer in objective-c.

I have an instance variable (primaryConnection) that should be updated dynamically to point to a local variable when it changes.

NSURLConnection *primaryConnection;

-(void) doSomething
{
  NSURLConnection *conn;
  primaryConnection = conn;

  conn = // set by something else

  // primaryConnection should now reflect the pointer that conn is pointing to, set by something else... but it doesn't?
}

Is it possible to declare a pointer to a pointer somehow? Or am I missing something?

A: 

You assign the pointer value of conn to primaryConnection before you have set conn, so conn and thus primaryConnection will probably point to garbage.

Keep in mind that you have to retain the NSURLConnection object before storing it as instance variable, otherwise the object will probably be released to early. So release the old primaryConnection, and then assign a new object to it, but also retain the new object.

JoostK
A: 

You need to set it to conn after conn has been set to where you want it.

UncleO
+2  A: 

Declare it as:

NSURLConnection **primaryConnection;

Set it as:

primaryConnection = &conn;

This is plain C stuff, and not specific to Objective-C. To access primaryConnection, you need to dereference it before sending messages to it:

NSURLConnection * theConn = *primaryConnection;
[theConn doSomethingElse];

Note, though that from your source code you pasted, this may not be safe. It appears you want to have doSomething on one thread, accessing a local variable, and are using primaryConnection from other threads to get a reference to that local variable? Why not just make it a normal instance variable?

Jason
See my answer; it is almost guaranteed that the person asking the question is wanting a pointer-to-a-pointer for the wrong reasons.
bbum
+16  A: 

You pretty much never ever want to do this, the one typical exception is when you want to pass a reference as an argument that may be filled in. See the use of (NSError **) throughout the APIs.

In particular, you do not want to declare an instance variable as NSConnection ** and then set it somewhere else; somewhere outside the object. That totally breaks encapsulation and is a sure sign that your code is poorly or, at the least, oddly designed.

Try this instead:

@interface MyClass:NSObject
{
    NSConnection *connection;
}

@property(retain) NSConnection *connection;
@end

@implementation MyClass
@synthesize connection;
@end

And in whatever class / code needs to set the connection:

@implementation SomeOtherClass
- (void) configureConnection: (MyClass *) anObject
{
    NSConnection *aConnection;

    aConnection = ... initialize the connection ...

    anObject.connection = aConnection;
}
@end

That will preserve encapsulation and allow something else to set up the connection for MyClass. If this doesn't solve your problem, you will need to tell us what it is you are really trying to do.

bbum