0

I implementing custom subclass of the NSURLProtocol. I need to store my NSURLProtocol instance inside NSMutableURLRequest. Since [NSURLProtocol setProperty:forKey:inRequest:] raises warning Invalid protocol-property list if you try to store non-plist-serializable object, I do it like this:

- (void)startLoading {
    ...    
    // when I need to store an NSURLProtocol subclass
    [NSURLProtocol setProperty:[NSNumber numberWithLongLong:(long long)self] forKey:@"WebProxyURLProtocol" inRequest:mutableRequest];
    ...
}

and

// when I need to get an NSURLProtocol subclass back in NSURLSessionDelegate
- (NSURLProtocol *)protocolForTask:(NSURLSessionTask *)task {
    NSNumber *number = [NSURLProtocol propertyForKey:@"WebProxyURLProtocol" inRequest:task.originalRequest];
    return (__bridge NSURLProtocol *)(void *)number.longLongValue;
}

This works quite well. But is it safe and correct way to solve my problem, or I sometimes can get already deallocated object? Thanks!

KY1VSTAR
  • 395
  • 4
  • 16
  • It is extremely not safe. Why you can't use `registerClass:` and `canInitWithRequest:` methods? – Andrew Romanov Jul 17 '17 at 03:15
  • Or why you can't use Factory pattern here? – Andrew Romanov Jul 17 '17 at 03:16
  • @AndrewRomanov You have misunderstood me. I call [NSURLProtocol setProperty:forKey:inRequest:] in [NSURLProtocol startLoading]. I need to call [NSURLProtocol client]'s methods from NSURLSessionDelegate in another place. – KY1VSTAR Jul 17 '17 at 03:57

0 Answers0