NSOperation 未将子视图添加到主视图

发布于 2024-09-10 13:00:26 字数 865 浏览 2 评论 0原文

使用 NSOpation 时我遇到了奇怪的行为。 我正在调用一个函数(-createTagView)来创建一个 UIButton,然后将其添加到视图中。 由于某种原因,它没有添加它们。如果我从 NSOperation 外部调用该函数,一切都会正常。

有什么想法吗?谢谢。

这就是我创建 NSOperation 的方式(在 ViewController 对象内),

> NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(createTagView:) object:data];   
> [operationQueue addOperation:operation];
> [operation release];

这就是调用的函数([Tag view] 是 UIButton):

-(void) createTagView:(NSMutableArray *) data
{
 NSInteger t_id  = (NSInteger)[data objectAtIndex:0];
 NSString *t_name = (NSString *)[data objectAtIndex:1];
 NSString *t_rawname = (NSString *)[data objectAtIndex:2];


 Tag *t = [[Tag alloc] initWithId:(NSInteger)t_id name:t_name rawname:t_rawname];

 [self.view addSubview:[t view]];

 [t release];
}

I am running into an strange behavior when using NSOpeation.
I am calling a function (-createTagView) that creates an UIButton to then add it to a view.
For some reason it's not adding them. If I call the function from outside the NSOperation everything works fine.

Any ideas? Thanks.

This how I create the NSOperation (within a ViewController object)

> NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(createTagView:) object:data];   
> [operationQueue addOperation:operation];
> [operation release];

And this is the function called ([Tag view] is the UIButton):

-(void) createTagView:(NSMutableArray *) data
{
 NSInteger t_id  = (NSInteger)[data objectAtIndex:0];
 NSString *t_name = (NSString *)[data objectAtIndex:1];
 NSString *t_rawname = (NSString *)[data objectAtIndex:2];


 Tag *t = [[Tag alloc] initWithId:(NSInteger)t_id name:t_name rawname:t_rawname];

 [self.view addSubview:[t view]];

 [t release];
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若言繁花未落 2024-09-17 13:00:26

NSOperation 使用单独的线程来运行,必须在主线程内调用 [addSubview: ]。有一个方法 [object PerformSelectorOnMainThread:withObject:waitUntilDone:] - 您可以使用它来添加子视图。

[self.view performSelectorOnMainThread:@selector(addSubview:) withObject:aView waitUntilDone:YES];

NSOperation uses a separate thread to run, you must call [addSubview: ] within the main thread. There is a method [object performSelectorOnMainThread:withObject:waitUntilDone:] - you can use it to add the subview.

[self.view performSelectorOnMainThread:@selector(addSubview:) withObject:aView waitUntilDone:YES];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文