@interface Stream(){ NSinputStream *inputStream; NSOutputStream *outputStream;}-(ID)init{ self = [super init]; if (self) { inputStream = nil; outputStream = nil; } return self;}-(int)streamOpenWithIp:(Nsstring *)ip withPortNumber:(int)portNumber;{ CFReadStreamRef readStream; CFWriteStreamRef writeStream; CFStreamCreatePairWithSocketToHost(kcfAllocatorDefault,(__brIDge CFStringRef)ip,portNumber,&readStream,&writeStream); if(readStream && writeStream) { //Setup inpustream inputStream = (__brIDge NSinputStream *)readStream; [inputStream setDelegate:self]; [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [inputStream open]; //Setup outputstream outputStream = (__brIDge NSOutputStream *)writeStream; [outputStream setDelegate:self]; [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [outputStream open]; }}- (int)streamClose;{ CFReadStreamSetProperty((__brIDge CFReadStreamRef)(inputStream),kcfStreamPropertyShouldCloseNativeSocket,kcfBooleanTrue); CFReadStreamSetProperty((__brIDge CFReadStreamRef)(outputStream),kcfBooleanTrue); //Close and reset inputstream [inputStream setDelegate:nil]; [inputStream close]; [inputStream removeFromrunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; inputStream = nil; //Close and reset outputstream [outputStream setDelegate:nil]; [outputStream close]; [outputStream removeFromrunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; outputStream = nil;}
当我多次打开和关闭流时,此代码工作正常.当我使用Instruments检查我的应用程序内存泄漏时,它说CFStreamCreatePairWithSocketToHost函数泄漏了72%的内存.有人知道我做错了什么吗?我无法弄明白.
解决方法 添加CFRelease((CFStreamRef)inputStream);和CFRelease((CFStreamRef)outputStream);在streamClose方法中.当CFStreamCreatePairWithSocketToHost返回时,readStream和writeStream的所有权将传递给您:
Ownership follows the Create Rule in Memory Management Programming GuIDe for Core Foundation.
即使使用ARC,也需要明确释放Core Foundation对象:
The compiler does not automatically manage the lifetimes of Core Foundation objects; youmust call CFRetain and CFRelease (or the corresponding type-specific variants) as dictated by the Core Foundation memory management rules (see Memory Management Programming GuIDe for Core Foundation).
或者,更改此行(以及outputStream的相应行):
inputStream = (__brIDge NSinputStream *)readStream;
至:
inputStream = (__brIDge_transfer NSinputStream *)readStream;
这是因为readStream具有ARC未知的优秀保留计数.通过给ARC指定此指针的所有权,您授予它在适当时间释放指针的权限.进一步阅读:1,2
总结以上是内存溢出为你收集整理的iOS中的CFStreamCreatePairWithSocketToHost内存泄漏全部内容,希望文章能够帮你解决iOS中的CFStreamCreatePairWithSocketToHost内存泄漏所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)