我嘗試將Objective-C框架用於我的項目,並在將Objective-C代碼轉換爲Swift時遇到一些問題。將Objective-C代碼轉換爲Swift時EXC_BAD_ACCESS
其中的API:
- (void)ioFrameChannel:(PTChannel*)channel didReceiveFrameOfType:(uint32_t)type tag:(uint32_t)tag payload:(PTData*)payload
payload.data是這樣的結構:
typedef struct _PTExampleTextFrame {
uint32_t length;
uint8_t utftext[0];
} PTExampleTextFrame;
我想PTExampleTextFrame.utftext
這是一個消息從框架發送
所以我創建了一個本地的struct
:
struct CPTExampleTextFrame {
var length: UInt32
var utf8text: UnsafePointer<UInt8>
}
而且這樣寫:
var textFrame = UnsafePointer<CPTExampleTextFrame>(payload.data).memory
textFrame.length = CFSwapInt32(textFrame.length)
print(textFrame.length) // textFrame.length is correct!
let message = NSString(bytes: textFrame.utf8text, length: Int(textFrame.length), encoding: NSUTF8StringEncoding) // error
print(message)
But I get an error: EXC_BAD_ACCESS(code=1,address=0x31)
誰能告訴我是什麼問題?
而且也是我給你的框架的例子是在Objective-C:
- (void)ioFrameChannel:(PTChannel*)channel didReceiveFrameOfType:(uint32_t)type tag:(uint32_t)tag payload:(PTData*)payload {
if (type == PTExampleFrameTypeTextMessage) {
PTExampleTextFrame *textFrame = (PTExampleTextFrame*)payload.data;
textFrame->length = ntohl(textFrame->length);
NSString *message = [[NSString alloc] initWithBytes:textFrame->utf8text length:textFrame->length encoding:NSUTF8StringEncoding];
[self appendOutputMessage:[NSString stringWithFormat:@"[%@]: %@", channel.userInfo, message]];
} else if (type == PTExampleFrameTypePing && peerChannel_) {
[peerChannel_ sendFrameOfType:PTExampleFrameTypePong tag:tag withPayload:nil callback:nil];
}
}
感謝您的諮詢!最後,我使用了Objective-C方法來構建我需要的信息,並且只需要我一分鐘......所以,我認爲,在某些情況下,Swift並不總是Swift項目中的最佳選擇。 – Duelsol