指向objective-c中的指针?

mwa*_*her 6 pointers objective-c

我想声明一个指向objective-c中指针的指针.

我有一个实例变量(primaryConnection),它应该动态更新,以便在更改时指向局部变量.

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?
}
Run Code Online (Sandbox Code Playgroud)

是否有可能以某种方式声明指针指针?或者我错过了什么?

bbu*_*bum 24

您几乎从未想过这样做,一个典型的例外是您希望将引用作为可填写的参数传递.请参阅(NSError **)整个API 的使用.

特别是,您希望将实例变量声明为NSConnection **然后将其设置为其他位置; 在对象之外的某个地方.这完全破坏了封装,并且确实表明您的代码很差,或者至少是奇怪的设计.

试试这个:

@interface MyClass:NSObject
{
    NSConnection *connection;
}

@property(retain) NSConnection *connection;
@end

@implementation MyClass
@synthesize connection;
@end
Run Code Online (Sandbox Code Playgroud)

无论在类/代码中需要设置连接:

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

    aConnection = ... initialize the connection ...

    anObject.connection = aConnection;
}
@end
Run Code Online (Sandbox Code Playgroud)

这将保留封装并允许其他东西为MyClass建立连接.如果这不能解决您的问题,您需要告诉我们您的确想要做什么.


Jas*_*son 5

声明为:

NSURLConnection **primaryConnection;
Run Code Online (Sandbox Code Playgroud)

将其设置为:

primaryConnection = &conn;
Run Code Online (Sandbox Code Playgroud)

这是普通的C东西,并不是Objective-C特有的.要访问primaryConnection,您需要在向其发送消息之前取消引用它:

NSURLConnection * theConn = *primaryConnection;
[theConn doSomethingElse];
Run Code Online (Sandbox Code Playgroud)

请注意,尽管您粘贴了源代码,但这可能不安全.看来你想拥有doSomething一个线程,访问一个局部变量,并primaryConnection从其他线程使用来获取对该局部变量的引用?为什么不把它变成普通的实例变量呢?