是否可以使用通知回复到IOS应用程序的主线程?(cf performSelectorOnMainThread).也就是说,为此目的有没有任何gottcha?
背景
例如
[[NSNotificationCenter defaultCenter] postNotificationName:@"ModelChanged" object:self];
Run Code Online (Sandbox Code Playgroud) 好吧,所以说我有第二个线程正在运行,但它想在主线程上操作一些东西,比如一个UI项目.
-(void)backgroundThread
{
[myButton performSelectorOnMainThread:@selector(setEnabled:) withObject:(BOOL)YES waitUntilDone:YES];
// right here, how could i pass this BOOL to the function
}
Run Code Online (Sandbox Code Playgroud)
我尝试过使用NSNumber's numberWithBOOL,但NSButton不接受它.
我试图更好地理解操作和线程,并查看AFNetworking的AFURLConnectionOperation子类,例如,真实世界的源代码.
我目前的理解是当实例NSOperation被添加到操作队列时,队列等管理负责执行操作的线程.在苹果公司的文档,NSOperation它指出,即使子类返回YES的-isConcurrent操作将始终在一个单独的线程来启动(为10.6).
基于Apple在线程编程指南和并发编程指南中强大的语言,管理线程似乎最好留给内部实现NSOperationQueue.
但是,AFNetworking的AFURLConnectionOperation子类产生了一个新的NSThread,并且操作-main方法的执行被推送到此网络请求线程.为什么?为什么这个网络请求线程是必要的?这是一种防御性编程技术,因为该库旨在供广大受众使用吗?调试库的消费者是不是更麻烦?在专用线程上进行所有网络活动是否有(微妙的)性能优势?
(
在1月26日添加)在Dave Dribin 的博客文章中,他演示了如何使用NSURLConnection的具体示例将操作移回主线程.
我的好奇心来自Apple的线程编程指南中的以下部分:
保持你的线程合理繁忙.
如果您决定手动创建和管理线程,请记住线程占用宝贵的系统资源.您应该尽力确保为线程分配的任何任务都是合理的长寿和高效的.与此同时,您不应该害怕终止花费大部分时间闲置的线程.线程使用大量内存,其中一些是有线的,因此释放空闲线程不仅有助于减少应用程序的内存占用,还可以释放更多物理内存供其他系统进程使用.
在我看来,AFNetworking的网络请求线程没有"保持相当忙碌"; 它正在运行一个无限的while循环来处理网络I/O. 但是,请注意,这就是问题的关键 - 我不知道,我只是在猜测.
AFURLConnectionOperation对操作,线程(运行循环?)和/或GCD的具体问题的任何洞察或解构都将非常有利于填补我理解的空白.
objective-c nsoperation nsthread nsoperationqueue afnetworking
在iOS中发生某些事件之前,如何在NSThread内等待?
例如,我们创建了一个NSThread并启动了一个线程循环.在线程循环内部,有条件检查消息队列是否有任何消息.如果有消息,那么它将调用相应的方法来执行某些操作,否则它应该等到消息队列填充新消息.
是否有任何API或方法可用于等待某些事件发生?
For Example
NSThread *thread = [NSThread alloc]....@selector(threadLoop)
- (void)threadLoop
{
// Expecting some API or method that wait until some messages pushed into the message queue
if (...) {
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助应该被赞赏.
我的场景看起来像这样:我有一个类中有一个函数,这个函数使用NSURLSession向服务器发出POST请求.在另一个不在该类中的函数中,我将该函数调用其中的任务,我认为它是异步运行的.我遇到以下问题:当我从服务器下载JSON响应并将其写入变量并返回它时,我写的变量仍为零,因为它没有等待线程/任务完成下载并返回初始值为nil.
所以我的问题是如何等待该任务完成然后继续整个程序.
这是我的具有请求功能的类:
class DownloadTask {
var json:NSDictionary!
var cookie:String!
var responseString : NSString = ""
func forData(completion: (NSString) -> ()) {
var theJSONData:NSData!
do {
theJSONData = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions())
} catch _ {
print("error")
}
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
if cookie != nil {
request.setValue(cookie, forHTTPHeaderField: "Cookie")
}
request.HTTPBody = theJSONData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error")
return
} else { …Run Code Online (Sandbox Code Playgroud) 在Obj-C中,简单来说意味着什么; "CoreData不是线程安全的"
或者一般来说什么是"非线程安全"?
我只是在几秒钟的延迟后尝试关闭一个NSPanel,但我无法启动我的NSTimer.如果我明确地在它上面调用fire方法,它会触发,但它永远不会自行解决.这是我的代码:
- (void)startRemoveProgressTimer:(NSNotification *)notification {
NSLog(@"timer should start");
timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(removeProgress:) userInfo:nil repeats:NO];
}
- (void)removeProgress:(NSTimer *)timer {
[progressPanel close];
}
Run Code Online (Sandbox Code Playgroud)
我的代码中确实有一些线程.我认为这是弄乱我的计时器的原因.
-(void)incomingTextUpdateThread:(NSThread*)parentThread {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//mark the thread as running
readThreadRunning = TRUE;
const int BUFFER_SIZE = 100;
char byte_buffer[BUFFER_SIZE]; //buffer for holding incoming data
int numBytes = 0; //number of bytes read
NSString *text; //incoming text from the serial port
[NSThread setThreadPriority:1.0];
//this will loop until the serial port closes
while …Run Code Online (Sandbox Code Playgroud) 当你使用线程时,你有任何偏好吗?一般来说,要使用以下任何一种技术:
NSOperationQueue是否简化了所有内容,因此在我们需要创建异步函数时更好用?
iphone objective-c nsthread nsoperationqueue grand-central-dispatch
Xcode的"线程列表"窗格显示了几个特殊线程的英文名称:com.apple.main-thread,com.apple.libdispatch-manager,com.dispatchfractal.opencl,com.dispatchfractal.opengl,com.apple.root.低优先级,但对于用户创建的线程,该字段只是空白.
有没有办法从我的应用程序以编程方式设置"线程名称"字段?例如,如果我有一个专门用于网络I/O的线程,我希望它在调试器中显示为"com.example.network-io"; 如果我生成五个工作线程,我希望能够将它们命名为"worker A","worker B"等.Xcode是否可以从我可以挂钩的某些API中获取其线程名称?也许是这样的CFAssignDebuggerNameToCurrentThread?:)

所以我有一个应用程序,它触发一系列异步事件,然后将结果写入缓冲区.问题是我希望缓冲区同步写入(在产生异步进程的线程中)
骨架代码就是这样
let Session = NSURLSession.sharedSession()
let TheStack = [Structure]()
//This gets called asynchronously, e.g. in threads 3,4,5,6,7
func AddToStack(The Response) -> Void {
TheStack.insertAt(Structure(The Response), atIndex: 0))
if output.hasSpaceAvailable == true {
// This causes the stream event to be fired on mutliple threads
// This is what I want to call back into the original thread, e.g. in thread 2
self.stream(self.output, handleEvent: NSStreamEvent.hasSpaceAvailable)
}
}
// This is in the main loop, e.g. thread 2
func stream(aStream: NSStream, …Run Code Online (Sandbox Code Playgroud) nsthread ×10
objective-c ×5
iphone ×4
ios ×3
swift ×2
afnetworking ×1
asynchronous ×1
cocoa ×1
macos ×1
nsoperation ×1
nsrunloop ×1
nstimer ×1
swift2 ×1
xcode ×1