开发者

How can I force an unused variable to be part of a block?

开发者 https://www.devze.com 2023-03-06 02:25 出处:网络
Considering the following code: - (void)downloadObjectUsingURL: (NSURL *)url; { id file = [self createFileForURL: url];

Considering the following code:

- (void)downloadObjectUsingURL: (NSURL *)url;
{
    id file = [self createFileForURL: url];
    Finalization objectFinalization = ^() {
        // we don't access url here, but it would be handy to see it in the debugger
        [file close];
    }
    id request = [self buildRequestFromURL: url];
    [object download: request
              toFile: file
        finalization: objectFinalization];
开发者_Go百科}

What is the easiest way to force url to be copied as part of objectFinalization's context, copied and passed as part of objectFinalization for the purposes of easier debugging?

I can think of a few possible answers, but none of them strike me as good. I can do NSLog(@"%@",url), but that causes spew. I can do a NSAssert(url,...); or if (url) {}, but both of these don't really express what I'm trying to do.


Wrap the call to NSLog() in #ifdef debug.. #endif


I thought of a nicer answer, but thanks to @NSResponder for making me think this way:

#if DEBUG
#define FORCE(a) NSParameterAssert(YES || a)
#else
#define FORCE(a)
#endif

This makes the code look like this:

- (void)downloadObjectUsingURL: (NSURL *)url;
{
    id file = [self createFileForURL: url];
    Finalization objectFinalization = ^() {
        FORCE(urL);
        [file close];
    }
    id request = [self buildRequestFromURL: url];
    [object download: request
              toFile: file
        finalization: objectFinalization];
}


Years later I discover the simplest answer. Inside the block, use:

(void)variable;

Example:

- (void)downloadObjectUsingURL: (NSURL *)url;
{
    id file = [self createFileForURL: url];
    Finalization objectFinalization = ^() {
        (void)url;
        [file close];
    }
    id request = [self buildRequestFromURL: url];
    [object download: request
              toFile: file
        finalization: objectFinalization];
}

If you only want in in debug:

- (void)downloadObjectUsingURL: (NSURL *)url;
{
    id file = [self createFileForURL: url];
    Finalization objectFinalization = ^() {
#if DEBUG
        (void)url;
#endif
        [file close];
    }
    id request = [self buildRequestFromURL: url];
    [object download: request
              toFile: file
        finalization: objectFinalization];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消