2014-09-29 42 views
0

我无法在任何stackoverflow主题中找到答案。我面对线程和类,我想在全球* .m文件中使用类控制器变量和操作。没有附加第二类。 这里是代码:可可线程和类声明连接

或者Controller.h

#import <Cocoa/Cocoa.h> 

@interface Controller : NSObject 
{ 
IBOutlet NSWindow *Main; 
IBOutlet NSButton *myButton; 
} 
- (void)awakeFromNib; 
- (IBAction)action:(id)sender; 
- (IBAction)Display(id)sender; 

@end 

Controller.m或者

#import "Controller.h" 

@implementation Controller 

- (void)awakeFromNib 
{ 

    //At this point i can reach any variable from Controller.h 

} 

- (IBAction)Display:(id)sender 

{ 

    //Same, i can reach any variable from Controller.h 

} 

//后关闭 “}” 和新的生产线开始,我不能调用[Display]或者Controller.h中的其他东西,我的线程代码就会出现在这里,并且我想要编写线程来调用Display,或者使用awakeFromNib变量,字符串和动作。

线程代码

#include assert.h 
#include pthread.h 

void* PosixThreadMainRoutine(void* data) 
{ 

    // I want to call here, example [Display click:self]; 
    // but i only see [Controller]... 
    int ac = 0; 
    while (ac < 8) 
    { 
     sleep(1); 
     printf("Test"); 
     ac++; 
    } 
    return NULL; 
} 
void LaunchThread() 
{ 

    // Create the thread using POSIX routines. 
    pthread_attr_t attr; 
    pthread_t  posixThreadID; 
    int    returnVal; 

    returnVal = pthread_attr_init(&attr); 
    assert(!returnVal); 
    returnVal = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); 
    assert(!returnVal); 

    int  threadError = pthread_create(&posixThreadID, &attr, &PosixThreadMainRoutine, NULL); 

    returnVal = pthread_attr_destroy(&attr); 
    assert(!returnVal); 
    if (threadError != 0) 
    { 
     // Report an error. 
    } 
} 

@end 

线程代码的工作100%,但我不能调用PosixThreadMainRoutine任何变量或函数,可以有人解释如何做到这一点? `

回答

0

如果你想在独立的线程与accesing到@interface方法/变量执行代码它能够更好地使用:

[NSThread detachNewThreadSelector:@selector(Display:) toTarget:self withObject:t];

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_apply(10, queue, ^(size_t i) { ///Thread code here });

在你的榜样不清楚 - 什么是[显示点击:自己];正如我看到显示 - 它的方法,但不是接口。另外PosixThreadMainRoutine()不是实例或类方法。这就是为什么你不能调用call方法。一般来说你没有访问权限,因为编译器不知道名称为Dispaly的接口,并且不知道click:方法的声明。

我sugest你的下一篇文章:From C++ to Objective-C

+0

我仍然面临同样的问题,显示为例,我想从线程执行[自我显示:(id)发件人]; ,对不起,我忘了添加在controller.h行中: - (IBAction)Display:(id)sender; – RepoStack 2014-09-29 11:26:14

+0

尝试在pthread_create的最后一个参数中传递self,然后在PosixThreadMainRoutine(void * data)中使用[(Controller *)data Display:nil]调用方法。但它并不是“可可风格”的发展。 – toohtik 2014-09-29 11:31:38

+0

不能通过自我,我得到未声明的标识符“自我”,并且你的行[(Controller *)数据显示:无]不做任何事情。你可以解释在哪里插入,或修改在pthread_create – RepoStack 2014-09-29 11:40:55

0

Controller.m或者

I deleted thread, and i used this example: 
[NSThread detachNewThreadSelector:@selector(Display:) toTarget:self withObject:nil]; 


- (IBAction)action:(id)sender{ 
[NSThread detachNewThreadSelector:@selector(Display:) toTarget:self withObject:nil]; 
} 

它是这样工作的魅力!我会保存代码,如果有人知道答案,我会尝试在正确的情况下。