我有一个 ViewController,我在其中调用另一个类(TCP 类)的方法,在其中与服务器建立 TCP 连接,这给了我一个响应。我想,当该 TCP 类从服务器获取响应时,从 ViewController 调用另一个方法。
问题:
- 我是个菜鸟。
- 我首先初始化并分配它 TCP 上的 View Controller ,并且我的所有变量都被重置(某些东西 我不想要的)。
那么...我能做些什么来纠正它呢?我只想调用已经在内存中分配的不同类的方法。
谢谢!
最佳答案
您可以将 ViewController 设置为 TCP 类的观察者。此链接解释了 Obj-C 中观察者模式的实现。 (与我使用的非常相似,但写得很好。)
http://www.a-coding.com/2010/10/observer-pattern-in-objective-c.html
我通常也喜欢将持久层与界面分开。我使用观察者或 KVO 来通知我的业务逻辑和 View Controller 某些内容发生了变化。
如果您愿意,您还可以通过提供的通知中心发送信息...
基本代码示例:
@implementation ExampleViewController
//...
- (void)viewDidLoad
{
[super viewDidLoad:animated];
[TCPClass subscribeObserver:self];
}
- (void)viewDidUnload
{
[super viewDidUnload:animated];
[TCPClass unsubscribeObserver:self];
}
- (void)notifySuccess:(NSString*)input
{
//Do whatever I needed to do on success
}
//...
@end
@implementation TCPClass
//...
//Call this function when your TCP class gets its callback saying its done
- (void)notifySuccess:(NSString*)input
{
for( id<Observer> observer in [NSMutableArray arrayWithArray:observerList] )
{
[(NSObject*)observer performSelectorOnMainThread:@selector(notifySuccess:) withObject:input waitUntilDone:YES];
}
}
//maintain a list of classes that observe this one
- (void)subscribeObserver:(id<Observer>)input {
@synchronized(observerList)
{
if ([observerList indexOfObject:input] == NSNotFound) {
[observerList addObject:input];
}
}
}
- (void)unsubscribeObserver:(id<Observer>)input {
@synchronized(observerList)
{
[observerList removeObject:input];
}
}
//...
@end
//Observer.h
//all observers must inherit this interface
@protocol Observer
- (void)notifySuccess:(NSString*)input;
@end
希望有帮助!
关于xcode - 从另一个类调用方法,而不重新初始化它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11548599/