将指针存储在NSNumber

时间:2017-07-17 01:48:33

标签: ios objective-c pointers nsnumber nsurlprotocol

我实现了NSURLProtocol的自定义子类。我需要将NSURLProtocol实例存储在NSMutableURLRequest中。如果您尝试存储非plist-serializable对象,[NSURLProtocol setProperty:forKey:inRequest:]会引发警告Invalid protocol-property list,我会这样做:

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

// 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;
}

这很有效。但这是解决我的问题的安全和正确的方法,或者我有时可以获得已经解除分配的对象?谢谢!

0 个答案:

没有答案