0

这是我在可可 ViewController.h 中实现“CFsocket”的代码

@interface ViewController : NSViewController
-(IBAction)start:(id)sender;
@property (strong, nonatomic) IBOutlet NSTextView  *CommandDisplay;

这是 ViewController.m

@implementation ViewController
@synthesize CommandDisplay=_CommandDisplay;

void AcceptCallBack(CFSocketRef socket,CFSocketCallBackType type,CFDataRef address,const void *data,void *info)
{
CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
// For a kCFSocketConnectCallBack that failed in the background, it is a pointer to an SInt32 error code; for a kCFSocketAcceptCallBack, it is a pointer to a CFSocketNativeHandle; or for a kCFSocketDataCallBack, it is a CFData object containing the incoming data. In all other cases, it is NULL.
CFSocketNativeHandle sock = *(CFSocketNativeHandle *) data;
CFStreamCreatePairWithSocket(kCFAllocatorDefault, sock, &readStream, &writeStream);


if (!readStream || !writeStream)
{
    close(sock);
    NSLog(@"CFStreamCreatePairWithSocket()Fail");
    return;
}

CFStreamClientContext streamCtxt = {0, NULL, NULL, NULL, NULL};
CFReadStreamSetClient(readStream, kCFStreamEventHasBytesAvailable, ReadStreamClientCallBack, &streamCtxt);
CFWriteStreamSetClient(writeStream, kCFStreamEventCanAcceptBytes, WriteStreamClientCallBack, &streamCtxt);

CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
CFWriteStreamScheduleWithRunLoop(writeStream, CFRunLoopGetCurrent(),kCFRunLoopCommonModes);

CFReadStreamOpen(readStream);
CFWriteStreamOpen(writeStream);
}

// readstream operatoion , use when client transmitted data
 void ReadStreamClientCallBack(CFReadStreamRef stream, CFStreamEventType eventType, void* clientCallBackInfo)
{
UInt8 buff[255];
CFReadStreamRef inputStream = stream;
CFReadStreamRead(stream, buff, 255);

_CommandDisplay.string=[self._CommandDisplay.string stringByAppendingString:[NSString stringWithFormat:@"SeverCreat failed\n"]];


NSLog(@"receive: %s",buff);
NSLog(@"%@",clientCallBackInfo);
CFReadStreamClose(inputStream);
CFReadStreamUnscheduleFromRunLoop(inputStream,CFRunLoopGetCurrent(),kCFRunLoopCommonModes);
inputStream = NULL;
 }

当我使用c函数时,它无法识别我合成的_CommandDisplay,但我需要将读取的数据打印到NSTextView,我该如何解决这个问题?

4

1 回答 1

0

在 Objective-C 中,综合属性foo由隐式实例变量支持_foo

  • 如果要直接访问实例变量,请使用_foo不带self.

  • 如果您想通过其合成的 getter 和 setter 访问属性self.foo(不带下划线)

self.CommandDisplay.string = [self.CommandDisplay.string stringByAppendingString:@"SeverCreat failed\n"];

或者

_CommandDisplay.string = [_CommandDisplay.string stringByAppendingString:@"SeverCreat failed\n"];

NSString stringWithFormat不需要,没有格式参数,也可以删除@synthesize行,也不需要。

一个小的旁注:

如果 C 函数超出了实现块的范围,则必须通过函数的参数传递对 NSTextView 实例的引用info,但在这种情况下它应该可以工作

于 2015-07-15T12:29:15.630 回答