ios - 线程完成时的 Objective C 设置图像

标签 ios objective-c multithreading uibutton thread-safety

我有一个按钮,我试图在线程完成时设置图像。我的代码似乎只是更改图像按钮毫无用处,但这是为了练习和做更大的事情。

目标:将 b0 的图像设置为 button_x.png(在项目中找到)。

问题:按钮图像没有改变,如果我在 Storyboard上找到的按钮与 viewController 按钮声明之间建立连接,我会因 -[UIButton setImage:] 而崩溃: 无法识别的选择器发送到实例 0x8b4c270

谢谢。

ViewController.h:

@interface ViewController : UIViewController {
    IBOutlet UIButton *b0;
    Game *instanceOfGame;
}

@property (nonatomic, strong) UIButton *b0;
@property (nonatomic, strong) Game *instanceOfGame;

@end

ViewController.m:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize instanceOfGame;
@synthesize b0;
static NSString *postName = @"123";


- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(post:) name:postName object:nil];
    instanceOfGame = [[Game alloc] init];
    [instanceOfGame start];
}

- (void) post: (NSNotification *) result {
    NSNumber *str = [result object];
    if (str == 0) {
        [self.b0 performSelectorOnMainThread:@selector(setImage: ) withObject:[UIImage imageNamed:@"button_x.png"] waitUntilDone:NO];
    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

游戏.h:

#import <Foundation/Foundation.h>

    @interface Game : NSObject
    @property (nonatomic, strong) NSNumber *choice;
    @property (nonatomic, strong) NSNotificationCenter *ns;
    -(void) start;
    @end

游戏.m:

#import "Game.h"

@implementation Game

NSNotificationCenter *ns;
@synthesize ns;
@synthesize choice;
static NSString *postName = @"123";

-(id) init {
    if (self = [super init]) {
        ns = [NSNotificationCenter defaultCenter];
    }
    return self;
}

-(void) start {
    [self performSelectorInBackground:@selector(loadData) withObject:Nil];
}

-(void) loadData {
    choice = 0;

    [ns postNotificationName:postName object:choice];
}

@end

最佳答案

UIButton 没有 setImage: 函数,因此抛出异常。

虽然它确实有这个功能:

- (void)setImage:(UIImage *)image forState:(UIControlState)state

尝试替换:

[self.b0 performSelectorOnMainThread:@selector(setImage: ) withObject:[UIImage imageNamed:@"button_x.png"] waitUntilDone:NO];

使用 GCD 调用正确的函数完成类似的实现:

dispatch_async(dispatch_get_main_queue(), ^{
   [self.b0 setImage:[UIImage imageNamed:@"button_x.png"] forState:UIControlStateNormal];
});

关于ios - 线程完成时的 Objective C 设置图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22369783/

相关文章:

ios - 两个日期之间的 NSDate

c# - 如果在原始数据访问周围只使用 lock 关键字,是否有可能在 C# 中创建死锁?

ios - 在 subview 的 UILabel 列表中查找文本

iphone - 在 xCode 5/iOS7 中使导航栏拉伸(stretch)到状态栏后面

c# - 如何检测主线程何时终止?

multithreading - Spring Boot Web 应用程序中多个 REST 调用超时

ios - 在 UIWebView 中加载网页时出错

具有交叉滚动功能的 iOS UICollectionView Gallery

ios - 从服务中获取值

objective-c - 计算左侧 UIBarButtonItem 宽度