gpt4 book ai didi

iphone - 单例实现从服务器读/写

转载 作者:行者123 更新时间:2023-11-29 03:43:51 26 4
gpt4 key购买 nike

我正在尝试实现一个单例来从简单的聊天服务器读取/写入。我使用单例模型,以便我可以访问数据并从所有 View Controller 写入。

我的单例代码:

#import "ChatDataController.h"

@implementation ChatDataController
{
ChatDataController * anotherSingles;
}

@synthesize enString;
@synthesize enInt;


+(ChatDataController *) singlOjb {

static ChatDataController * single=nil;

@synchronized(self)
{
if(!single)
{
single = [[ChatDataController alloc] init];
}
}

return single;
}


// We can still have a regular init method, that will get called the first time the Singleton is used.
- (id)init
{
self = [super init];

if (self) {
// Work your initialising magic here as you normally would

[self initNetworkCommunication];
}

return self;
}

// Open connection to server
- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", 8080, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;

[inputStream setDelegate:self];
[outputStream setDelegate:self];

[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

[inputStream open];
[outputStream open];
}

- (void) sendMsg {
NSString *response = [NSString stringWithFormat:@"iam:TestString"];
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}

@end

问题是,当我从 init 方法运行 [self initNetworkCommunication]; 时,我的应用程序崩溃并出现错误:(lldb)

检测到线路中断:inputStream = (__bridge NSInputStream *)readStream;

知道我做错了什么吗?

编辑:这是我应该这样做的方式吗?

最佳答案

首先,你的单例代码应该是这样的......

+ (ChatDataController *)sharedInstance
{
static dispatch_once_t once;
static ChatDataController *chatDataController;
dispatch_once(&once, ^ { chatDataController = [[ChatDataController alloc] init];});
return chatDataController;
}

接下来,我不确定这是否会解决,因为我不确定确切的问题,但我会这样做......

在您的 AppDelegate(或任何您需要启动流的地方)执行此操作...

[[ChatDataController sharedInstance] initNetworkCommunication];

这确保单例对象在调用其实例方法之前已完全实例化。

关于iphone - 单例实现从服务器读/写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17988427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com