gpt4 book ai didi

iphone - 为什么没有performSelectorOnMainThread : in NSObject Protocol?

转载 作者:行者123 更新时间:2023-11-29 13:48:31 26 4
gpt4 key购买 nike

最近我在开发应用程序。 iPhone(iOS) 项目。

我想知道为什么 NSObject 协议(protocol)中没有 performSelectorOnMainThread:。

我需要在主线程上调用委托(delegate)的方法,因为它们必须处理 UI 组件。

这是我写的示例:

@protocol MyOperationDelegate;

@interface MyOperation : NSOperation {
id <MyOperationDelegate> delegate;
}
@property (nonatomic, assign) id <MyOperationDelegate> delegate;
@end

@protocol MyOperationDelegate <NSObject>
@optional
- (void) didFinishHandleWithResult:(NSDictionary *)result;
@end

@implementation MyOperation
@synthesize delegate;
- (void) main {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

NSDictionary *aDict = [[MySingleton sharedObject] fetchSomethingMeaningful];

//do something and call delegate
if ([delegate respondsToSelector:@selector(didFinishHandleWithResult:)]) {
[delegate performSelector:@selector(didFinishHandleWithResult:) withObject:
}

[pool release];
}
@end


@interface MyViewCon : UIViewController <MyOperationDelegate> {
NSOperationQueue *queue;
}
@end

@implementation MyViewCon
- (void) viewDidLoad {
MyOperation *op = [[MyOperation alloc] init];
op.delegate = self;
[queue addOperation:op];
[op release];
}

- (void) reloadUserInterface:(NSDictionary *)dict {
// Do reload data on User Interfaces.
}

- (void) didFinishHandleWithResult:(NSDictionary *)myDict {
// Couldn't execute method that's handling UI, maybe could but very slow...
// So it must run on main thread.
[self performSelectorOnMainThread:@selector(reloadUserInterface:) withObject:myDict];
}
@end

我可以在 MyOperation 类的主线程上运行 didFinishHandleWithResult: delegate 方法吗?

从这里开始,我每次调用 MyOperation 实例时都会实现 UI 处理方法。任何建议都会对我有所帮助。

最佳答案

让我们试试:

dispatch_async(dispatch_get_main_queue(), ^{

//your main thread code here

});

关于iphone - 为什么没有performSelectorOnMainThread : in NSObject Protocol?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6134489/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com