如何在视图控制器之间传递打开的套接字(故事板)

时间:2012-12-30 17:19:13

标签: objective-c ios6 storyboard gcdasyncsocket

Xcode iOS 6与故事板。我正在为现有程序添加聊天功能。我正在使用GCDAsyncSocket。 当我呆在一个viewcontroller中时,一切都很完美。我需要从许多viewcontrollers访问open socket。我还需要从这些viewcontrollers访问GCDASYNCSOCKET。

有没有人有一些可能对我有帮助的示例代码?

使用perpareforsegue是否允许我通过开放套接字? 我见过的任何单例似乎都没有考虑像GCDASYNCSOCKET那样已经存在的类,但似乎没有用。

请帮我一些实例。

Singleton.m

#import "SocketConnection.h"
#import "GCDAsyncSocket.h"



@implementation SocketConnection

static GCDAsyncSocket *socket;

+ (SocketConnection *)getInstance;

{

static dispatch_once_t once;
static SocketConnection *instanceOfSocketConnection;
dispatch_once(&once, ^ {instanceOfSocketConnection =[[SocketConnection alloc] init];});
return instanceOfSocketConnection;
}
- (id)init
{
NSString *host = @"xxx.xxxxx.com";
uint16_t port = 5467;


if (socket == nil)
{
    socket = [[GCDAsyncSocket alloc] initWithDelegate:self         delegateQueue:dispatch_get_main_queue()];
}

if (![socket isConnected])
{
    NSError *error = nil;

    if (![socket connectToHost:host onPort:port error:&error])
    {
        NSLog(@"Error connecting: %@", error);
    }

}

return self;
}

-(void) socket:(GCDAsyncSocket *) socket didConnectToHost:(NSString *)host port:(uint16_t)port
{
NSLog(@"Connected");

}


@end

Singleton.h

#import <Foundation/Foundation.h>
#import "GCDAsyncSocket.h"

@interface SocketConnection : NSObject{}


+ (SocketConnection *)getInstance;
@end

此代码(单例)给我一个错误

当我尝试从另一个viewcontroller访问它时,我收到一个错误(从SocketConnection分配给'GCDAsyncSocket“_strong'的指针类型不兼容)

socket = [SocketConnection getInstance];

1 个答案:

答案 0 :(得分:1)

查看代码时,我发现您的错误(incompatible pointer types assigning to 'GCDAsyncSocket" _strong' from SocketConnection)清楚地描述了崩溃的原因。

+getInstance方法中,您返回SocketConnection,并尝试将其指定为GCDAsyncSocket类型的ivar。创建属性或其他方法以提供对内部socket变量的访问权。

相关问题