RestKit iOS : Simple request error

2019-07-20 04:58发布

问题:

I'm newbie on iOS development and I'm currently testing RestKit 0.9.3 for iOS with xCode 4.2 using ARC and I encounter some problem for a simple get request.

I following this tutorial : https://github.com/RestKit/RestKit/wiki/Tutorial-%3A-Introduction-to-RestKit

I try to send a simple get request to my webservices on TouchUpInside a UIButton.

But I receive an " EXC_BAD_ACCESS " : [6373:fb03] *** -[DataAccess respondsToSelector:]: message sent to deallocated instance 0x8275160

The application stop at this line, on RKRequest.m file :

if ([self.delegate respondsToSelector:@selector(requestDidStartLoad:)]) {
    [self.delegate requestDidStartLoad:self];
}

My code :

MyViewController.m :

- (IBAction)myAction:(id)sender {
    DataAccess *data = [DataAccess alloc];
    [data sendRequests];
}

DataAccess.m :

@implementation DataAccess

-(void)sendRequests {

    [RKClient clientWithBaseURL:SERVER_URL username:SERVER_USERNAME password:SERVER_PASSWORD];  
    [[RKClient sharedClient] get:@"/myDistantAction" delegate:self];
}

#pragma mark - Delegate

-(void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response {

    if ([response isOK]) {
        NSLog(@"Retrieved : %@", [response bodyAsString]);
    }
}

@end

I searched on the Internet but I didn't found the solution

Someone could help me ?

Thanks,

回答1:

This may be one solution. I changed your code to use a singleton. I think the problem is when the callback function is called because he can no longer access the instance.

DataAccess.m:

@implementation DataAccess

static singleton *DataAccess= nil;

+ (DataAccess*)getInstance
{
    if (singleton == nil) {
        singleton = [[DataAccess alloc] init];
    }
    return singleton;
}

-(void)sendRequests {

    [RKClient clientWithBaseURL:SERVER_URL username:SERVER_USERNAME password:SERVER_PASSWORD];  
    [[RKClient sharedClient] get:@"/myDistantAction" delegate:self];
}

#pragma mark - Delegate

-(void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response {

    if ([response isOK]) {
        NSLog(@"Retrieved : %@", [response bodyAsString]);
    }
}

@end

MyViewController.m:

- (IBAction)myAction:(id)sender {
    DataAccess *data = [DataAccess getInstance];
    [data sendRequests];
}