当一个对象在ios中执行一个方法时,有没有什么解决方案可以发布一个通知

当一个对象在ios中执行一个方法时,有没有什么解决方案可以发布一个通知,ios,objective-c,Ios,Objective C,在那里。我上了2节课 @implemention A -(void) method1{ something; } @end @implemention B -(void) method2{ something } @end 如果不能修改A类的实现,当调用A中的method1时,有没有办法调用B中的method2?试试这个 可以在Method1中创建类对象 -(void) method1 { B *b = [[B alloc] init ]; // Create object

在那里。我上了2节课

@implemention A

-(void) method1{
something;
}
@end

@implemention B

-(void) method2{
 something
}
@end
如果不能修改A类的实现,当调用A中的method1时,有没有办法调用B中的method2?

试试这个

可以在Method1中创建类对象

-(void) method1
{
     B *b = [[B alloc] init ]; // Create object of class B 
     b.method2   // call method of class B
}
试试这个

可以在Method1中创建类对象

-(void) method1
{
     B *b = [[B alloc] init ]; // Create object of class B 
     b.method2   // call method of class B
}

听起来你好像在试图做一些更古怪的事情,但是如果没有进一步的信息,你很难给你其他的建议

不过。一种不需要更改类A实现的方法是子类A并重写方法实现:

- method1 {
    [super method1]; // forward the call on to class A

    // Now you can do what ever you want
    // Post a notification or call method1 on an instance of class B
}

听起来你好像在试图做一些更古怪的事情,但是如果没有进一步的信息,你很难给你其他的建议

不过。一种不需要更改类A实现的方法是子类A并重写方法实现:

- method1 {
    [super method1]; // forward the call on to class A

    // Now you can do what ever you want
    // Post a notification or call method1 on an instance of class B
}
B类的
viewDidLoad()
中添加观察者

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method2) name:@"method1Executed" object:nil];
class A
method1()
中添加以下代码

[[NSNotificationCenter defaultCenter] postNotificationName:@"method1Executed" object:nil];
B类的
viewDidLoad()
中添加观察者

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(method2) name:@"method1Executed" object:nil];
class A
method1()
中添加以下代码

[[NSNotificationCenter defaultCenter] postNotificationName:@"method1Executed" object:nil];


你想做的事很相似。小心处理。在这里(objective-c和ios论坛),你会发现有很多东西值得一读,但还是要从这里开始了解你想做什么。小心处理。在这里(objective-c和ios论坛),你会发现有很多东西可以阅读,但还是会从这里开始,关于

你说的不能修改是什么意思?我不完全确定你的意思,但委托/协议似乎是解决这个问题的方法。我的意思是我不能在实现a中插入任何新代码。是的,我知道委托和协议,我想要的是有一种方法,我可以在对象的方法执行中添加类似于观察者的东西。我的直觉反应是,“使用继承”,但如果不知道它背后的动机,就不可能说这是否是正确的解决方案。你说不能修改是什么意思?我不完全确定你的意思,但委托/协议似乎是解决这个问题的方法。我的意思是,我不能在实现a中插入任何新代码。是的,我知道委托和协议,我想要的是有一种方法,我可以在对象的方法执行中添加类似观察者的东西。我的直觉反应是,“使用继承,”但是如果不知道背后的动机,就不可能说这是不是正确的解决方案。OP不能修改A的实现。是的,不能修改。我尝试在ios运行时函数中找到一些方法。然后尝试重写类1的method1。OP无法修改A的实现。是的,无法修改。我试图在ios运行时函数中找到一些方法。而不是试图覆盖类1的方法1。我写了同样的东西,我认为这是你不能触摸类A时唯一要做的事情。我写了同样的东西,我认为这是你不能触摸类A时唯一要做的事情。