如何初始化对象并覆盖目标c中的方法?

时间:2013-01-22 14:39:56

标签: objective-c method-overriding

与其他语言一样,我们可以在initialization期间创建一个对象并覆盖对象中的方法。请帮帮我怎么办?

例如:

    public class DemoInitAndOverride {

    public void handleMessage(){}

}

在另一个班级

    public class SampleClass {

    public void doSomeThing(){
        DemoInitAndOverride demo = new DemoInitAndOverride(){
            @Override
            public void handleMessage() {
                // TODO Auto-generated method stub
                super.handleMessage();
            }
        };
    }

}
****EDIT:****

感谢大家提供可能的解决方案和建议。我认为现在提供一些有助于您提供解决方案的要求的详细信息非常重要。

处理程序概念类似于Android Framework,其中处理程序用于在2个线程或2个方法之间传递消息。请参阅下面的代码演示:

UI类(这里用户单击一个按钮,使用处理程序将请求分派给处理器类)

这是演示处理程序

/**
 * 
 * Used for thread to thread communication.
 * Used for non UI to UI Thread communication.
 *
 */
public class DemoHandler {

    public void handleMessage(Messages message){}

    final public void sendMessage(final Messages message){
        //Calling thread is platform dependent and shall change based on the platform
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (this) {
                    handleMessage(message);
                }
            }
        });
    }
}

这是一个简单的消息类

public class Messages {
    public Object myObject;

    //other hash map (key, values) and get data put data etc
}

这是简单的用户界面类演示代码:

public class UIClass {

    public UIClass(){
        //INIT
    }
    void onClick(int id){
        //Some Button is clicked:
        //if id == sendParcel
        //do
        TransactionProcessor.getInstance().sendParcel(handler, "Objects");
    }

    DemoHandler handler = new DemoHandler(){
        public void handleMessage(Messages message) {
            //Inform the UI and Perform UI changes
            //data is present in the messages
        };
    };
}

这是示例事务处理器类

公共类TransactionProcessor {

public static TransactionProcessor getInstance(){
    return new TransactionProcessor(); //for demonstration
}
//Various Transaction Methods which requires calling server using HTTP and process there responses:
public void sendParcel(final DemoHandler uiHander, String otherdetailsForParcel){
    //INIT Code and logical code
    //Logical Variables and URL generation
    String computedURL = "abc.com/?blah";
    DemoHandler serverConnectionHandler = new DemoHandler(){
        @Override
        public void handleMessage(Messages message) {
            super.handleMessage(message);
            //Process server response:
            //create a new message for the UI thread and dispatch
            Messages response = new Messages();
            //add details to messages
            //dispatch
            uiHander.sendMessage(response );
        }
    };
    new Thread(new ServerConnection(computedURL, serverConnectionHandler));
}
public void sendEmail(final DemoHandler uiHander, String otherdetailsForEmail){
    //SAME AS SEND PARCEL WITH DIFFERENT URL CREATION AND RESPONSE VALIDATIONS
}
public void sendNotification(final DemoHandler uiHander, String otherdetailsForNotifications){
    //SAME AS SEND PARCEL WITH DIFFERENT URL CREATION AND RESPONSE VALIDATIONS
}

}

2 个答案:

答案 0 :(得分:0)

在Objective-C中不是那么容易做到的,但这应该有效。它用自己的实现替换doSomething的{​​{1}}方法,并返回该类的新实例。但请注意,一旦完成此操作,新实现仍然适用于所有类的新实例,而不仅仅是单个实例。

DemoInitAndOverride

答案 1 :(得分:0)

这是一个令人讨厌的问题,我建议创建一个子类或其他东西。

这是你的答案,它基本上是相同的,但在运行时。继续冒险:

导入此内容:

#import <objc/runtime.h>

并将此代码添加到以下任何位置:

- (void)methodName {
    // whatever you want to do in there
}

在你的功能中:

Class subclass;
// Verifiy that you haven't created it already
subclass = objc_getClass("SampleClassSubclass");
if (!subclass) {
    // Generate a new class, which will be subclass of your SampleClass
    subclass = objc_allocateClassPair(subclass, "SampleClassSubclass", 0);
    // Obtain the implementation of the method you want to overwrite
    IMP methodImplementation = [self methodForSelector:@selector(methodName)];
    // With that implementation, replace the method
    class_replaceMethod(subclass, @selector(methodName), methodImplementation, "@@:");
    // Register the class you just generated
    objc_registerClassPair(subclass);
}

SampleClass *obj = [[subclass alloc] init];