Pointer to a pointer in objective-c?

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

I have an instance variable (primaryConnection) that must be dynamically updated 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 there any way to declare a pointer to a pointer? Or am I missing something?

+6
pointers objective-c
source share
4 answers

You almost never want to do this, the only typical exception is that you want to pass the link as an argument that can be populated. See usage (NSError **) in all APIs.

In particular, you do not want to declare an instance variable as NSConnection ** , and then set it somewhere else; somewhere outside the facility. This completely breaks the encapsulation and is a sure sign that your code is poor or at least weirdly designed.

Try this instead:

 @interface MyClass:NSObject { NSConnection *connection; } @property(retain) NSConnection *connection; @end @implementation MyClass @synthesize connection; @end 

And in any class / code you need to establish a connection:

 @implementation SomeOtherClass - (void) configureConnection: (MyClass *) anObject { NSConnection *aConnection; aConnection = ... initialize the connection ... anObject.connection = aConnection; } @end 

This will preserve encapsulation and allow something else to configure the connection for MyClass. If this does not solve your problem, you need to tell us exactly what you are trying to do.

+24
source share

Declare it as:

 NSURLConnection **primaryConnection; 

Install it as:

 primaryConnection = &conn; 

This is a simple C material, and does not apply to Objective-C. To access primaryConnection, you need to dereference it before sending messages to it:

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

Please note that from your source code that you pasted, this may not be safe. It seems you want to have doSomething in one thread by accessing a local variable and using primaryConnection from other threads to get a link to this local variable? Why not just make it a regular instance variable?

+5
source share

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

Keep in mind that you must save the NSURLConnection object before storing it as an instance variable, otherwise the object will most likely be released early. So, release the old primaryConnection, and then assign it a new object, but also save the new object.

0
source share

You need to install it on the connection after the conn value is set to the place you need.

0
source share

All Articles