我正在尝试实现一个单例来从一个简单的聊天服务器读取/写入。我使用的是单例模型,这样我就可以访问数据并从我的所有视图控制器中写入。
我的单条代码:
#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
问题是,当我[self initNetworkCommunication];
从我的init
方法运行时,我的应用程序因错误而崩溃:(lldb)
在该行检测到中断:
inputStream = (__bridge NSInputStream *)readStream;
任何想法我做错了什么?
编辑:这是我应该这样做的方式吗?