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?
Objective-C Pointers in Detail You can define arrays to hold a number of pointers. Objective-C allows you to have pointer on a pointer and so on. Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
A pointer is a variable whose value is the address of another variable, e.g., stores the address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store variable addresses.
A pointer is a variable that stores the address of another variable. Unlike other variables that hold values of a certain type, pointer holds the address of a variable. For example, an integer variable holds (or you can say stores) an integer value, however an integer pointer holds the address of a integer variable.
Pointers in C programming are helpful to access a memory location. Pointers are an effective way to access the array structure elements. Pointers are used for the allocation of dynamic memory and the distribution. Pointers are used to build complicated data structures like a linked list, graph, tree, etc.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With