まず第一に、私は iOS 6 プログラミングの初心者です。アプリケーションの起動時にリモート サーバーへのソケット接続を開き、バックグラウンド スレッドで実行しようとしています。私はクラス - NetworkCommunication.h と、ストリームを読み書きできるようにしたい 3 つのビュー コントローラーを持っています。
コード:
NetworkCommunication.h:
#import <Foundation/Foundation.h>
@interface NetworkCommunication : NSObject {
NSInputStream* inputStream;
NSOutputStream* outputStream;
}
@property(retain) NSInputStream *inputStream;
@property(retain) NSOutputStream *outputStream;
-(void) initNetworkCommunication;
@end
NetworkCommunication.m
#import "NetworkCommunication.h"
NSOutputStream *outputStream;
NSInputStream *inputStream;
@implementation NetworkCommunication
@synthesize outputStream;
@synthesize inputStream;
- (id) init {
NSLog(@"Start!");
[self initNetworkCommunication];
return 0;
}
- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"127.0.0.1", 7000, &readStream, &writeStream);
inputStream = (__bridge_transfer NSInputStream *)readStream;
outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode ];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
[inputStream setProperty:NSStreamSocketSecurityLevelNegotiatedSSL
forKey:NSStreamSocketSecurityLevelKey];
[outputStream setProperty:NSStreamSocketSecurityLevelNegotiatedSSL
forKey:NSStreamSocketSecurityLevelKey];
NSDictionary *settings = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredCertificates,
[NSNumber numberWithBool:YES], kCFStreamSSLAllowsAnyRoot,
[NSNumber numberWithBool:NO], kCFStreamSSLValidatesCertificateChain,
kCFNull,kCFStreamSSLPeerName,
nil];
CFReadStreamSetProperty((CFReadStreamRef)inputStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);
CFWriteStreamSetProperty((CFWriteStreamRef)outputStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);
//[outputStream setProperty:NSStreamSocketSecurityLevelTLSv1 forKey:NSStreamSocketSecurityLevelKey];
NSString *response = @"HELLO from my iphone\n";
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}
@end
そして、次を使用して、任意のコントローラーまたは main.m でそれを開始しようとします: NetworkController *comm = [NetworkController new];
このコードに到達すると:
[inputStream open];
[outputStream open];
「Thead 1: EXC_BAD_ACCESS (code=1, address=0x10917df0)」が表示されました
私はそれを機能させる方法がわかりません。アプリの起動時にスレッドを開始し、NSOutputStream に書き込み、任意のコントローラーから NSInputStream を読み取ることができるようにしたいと考えています。出来ますか?もしそうなら、どのように?
前もって感謝します