Jacques Blom
Jacques Blom

Reputation: 1822

Make Objective-C method return anything

I am using this method below to get data from a URL, but I want to make it return an error if the statusCode is not equal to 200.

+ (NSData *)getData:(NSString *) url {
    NSURL *urlNS = [[NSURL alloc] initWithString:url];
    NSURLRequest * urlRequest = [NSURLRequest requestWithURL:urlNS];
    NSError * error = nil;
    NSHTTPURLResponse* urlResponse = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&urlResponse error:&error];
    int statusCode = [urlResponse statusCode];
    if(statusCode == 200) {
        return data;
    } else {
        //return the error object which is not NSData or which is converted to NSData
    }
}

My question

Can I somehow return my error (it will be the error variable defined above) in a non NSData object or can I maybe convert my error to NSData?

Upvotes: 0

Views: 1067

Answers (1)

matt
matt

Reputation: 534885

The usual convention is to return nil if there's an error.

If you also want to provide an error, the usual thing is to provide an extra parameter by indirection (NSError**).

Example:

+ (id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error

Return Value

A string created by reading data from the file named by path using the encoding, enc. If the file can’t be opened or there is an encoding error, returns nil.

Cocoa uses this pattern very heavily.

Upvotes: 11

Related Questions