【问题标题】:Class inheritance and custom ^block execution in objective C目标C中的类继承和自定义^块执行
【发布时间】:2014-01-11 10:49:20
【问题描述】:

我有一个应用程序,在该应用程序中我调用了一个 Web 服务来检索具有给定 ID 的 JSON 对象。 无论我在哪个类,获取对象的方法在系统上都是相同的,但成功块会有所不同(id est,处理部分)——例如使用 AFNetworking。

我正在寻找仅实现一次 getter 部分但能够自定义处理的正确方法。

下面这段代码是个好方法吗:

   -(void)getObjectWithId:(NSString*)id_{

    NSString *ns1 = [NSString stringWithFormat:@"%@%@%@",HOSTNAME,API_DETAIL,id_];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:ns1]];

    AFJSONRequestOperation *operation =[AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {


        //Here I want to do different processing task accordingly inheritance level // current class

        DLog(@"Response : %@ \n Request : %@",response,request);

        [self processObject:JSON];


    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {

        //Do failure stuff

    }];

    [operation start];

}

然后:

-(void)processObject:(id)JSON{


    //Customize according to current class

}

因此,所有子类都将继承自 getObjectWithId 并拥有自己的 processObject 实现

我还应该考虑什么?是正确的方法吗?

【问题讨论】:

    标签: ios objective-c json block afnetworking


    【解决方案1】:

    您的选择会起作用,但是将代码放在超类中会受到限制。如果限制适合您,请继续。

    另一种方法是创建一个辅助方法或管理器类来托管getObjectWithId: 方法,但要提供 2 个参数,其中第二个参数是一个将 JSON 作为参数的块。这样,该方法包含所有可重用代码,并且该块允许与原始 AFNetworking API 相同的任意使用。

    注意,“正确的方式”是适合您的情况的任何方式,也是可以理解和维护的......

    【讨论】:

    • 谢谢,在对我的代码进行高级审查后,我想我会在我的单例管理器中使用类(我认为)来包装一个 getter 方法,并将一个块作为参数传递接受 JSON。听起来不错!
    【解决方案2】:

    无需使用子类化。代表会帮助你。

    您可以创建一个实用程序类来检索 JSON 对象并为其声明协议。

    @protocol WebServiceDelegate <NSObject>
    - (void)didRetrivalJsonObject:(id)json ;
    @end
    

    你还需要修改方法

    - (void)getObjectWithId:(NSString*)id_ delegate:(id<WebServiceDelegate>)delegate
    {
        NSString *ns1 = [NSString stringWithFormat:@"%@%@%@",HOSTNAME,API_DETAIL,id_];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:ns1]];
        AFJSONRequestOperation *operation =[AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
            //Here I want to do different processing task accordingly inheritance level // current class
            DLog(@"Response : %@ \n Request : %@",response,request);
            [delegate processObject:JSON];
        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
            //Do failure stuff
        }];
        [operation start];
    }
    

    【讨论】:

    • 我会考虑下面的方法,但是谢谢,这看起来也很酷
    猜你喜欢
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多