简体   繁体   中英

ios ARC force retain NSURL

I am making a NSURL and passing it to a selector, which then passes it to another selector, etc. By the time it gets where it's going it logs just fine, but gives a sigabort when it's used. I suspect this means my object has been released by ARC. How can I make sure it stays around long enough to get used?

__strong NSURL *url = [[NSURL alloc] initWithString:str];

... passes to a selector
... passes to another
... and then to fetchVideoContent

- (void)fetchVideoContent:(NSURL *)url withGUID:(NSString *)guid;
{
    NSMutableURLRequest *req;
    req = [NSMutableURLRequest requestWithURL:url // <-- DIES ON THIS LINE (SIGABRT)
                                  cachePolicy:NSURLRequestUseProtocolCachePolicy
                              timeoutInterval:30.0];
    ...

That's the "strongest" thing I could think of and that still doesn't work. Any advice?

You need to ensure the initial url variable (__strong NSURL *url) continues to exist when the url object ends up at the fetchVideoContent method, if not, you'll get the error you're describing. Sounds to me like you're creating the url object in a method, using a local variable, and then passing that object through a few methods, that either cross to a new thread, or goes to the end of the runloop and back into the next run.

For example, if through the steps you've omitted, the current run loop ends, and the initial url variable goes out of scope, the url object will be freed, since nothing is actually holding on to it anymore. Passing the object to another method isn't enough to keep hold of it since no retain will be called on the parameter.

Short version is, make sure something holds onto url, you could make it a property of your class, an instance variable or even static if you'll only one instance of your class in use at a time.

First, you should verify that you are in fact dealing with a reference count issue -- run with zombies enabled.

I've no idea what all the URL is being passed through, but there are corner cases where explicit reference counting is required when ARC is enabled.

If MRC semantics are needed, you can use CFRetain and match that with a CFRelease , or you can create your own functions which are not compiled with ARC enabled.

Of course, you could simply use CFTypes instead (in this case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM