Scrungepipes
Scrungepipes

Reputation: 37581

Most efficient use of URLByAppendingPathComponent

My specific question is about using URLByAppendingPathComponent but the principle will be applicable to many other classes/methods and situations.

I have the following (abbreviated)code:

NSData *packageData = [[NSData alloc] initWithContentsOfURL:[myDirectoryURL URLByAppendingPathComponent:myFileURL]];

...

ret = [self.fileManager removeItemAtURL: [myDirectoryURL URLByAppendingPathComponent:myFileURL]];

So I am using NSURL:URLByAppendingPathComponent twice with the same parameters. My question is which is more efficient, doing it this way, or creating a new NSURL* and assigning the result of the call to URLByAppendingPathComponent into that and then using that as the parameter to initWithContentsOfURL and removeItemAtURL. I presume the second method is better but as I'm quite new to iOS and ARC want to double check. (What is the lifetime of the objects that will be created by this call? I'm using ARC and I presume their lifetime is therefore to the end of the scope of the function block in which they are used.)

Upvotes: 0

Views: 590

Answers (1)

David Dunham
David Dunham

Reputation: 8329

It's more efficient to save the URL rather than creating (and deallocating) it an extra time.

BUT, who cares? You should be asking which is the most clear code, that you will be able to understand and maintain later. You are never going to be loading from URLs in a tight loop, where efficiency might matter.

The DRY (don't repeat yourself) principle suggests that you make the URL once, because you have the code in only one place. That way, if something ever changes (e.g. you need to sanitize myFileURL against attacks), you only need to make the change in one place.

Upvotes: 0

Related Questions