Set pointers to nil after release?

前端 未结 4 835
臣服心动
臣服心动 2021-01-01 20:09

After releasing objects is it best to set the pointers to nil? Thats what I have been doing, just wanted to ask if its necessary, good practice or overkill?

         


        
4条回答
  •  不知归路
    2021-01-01 20:16

    At times this can be crucial, as I just found out. I use a camera in my game which keeps a pointer to a generic target. If you return to the main menu from a level then it clears the level from memory but keeps the camera and game layers.

    -(void) dealloc {
        [target release];
        target = nil;
        [super dealloc];
    }
    

    Since the camera will exist longer than the target, it's best to set target to nil, otherwise when the level loads again and you set a new target:

    -(void) setTarget:(CCNode *)aTarget {
        [target release];
        target = [aTarget retain];
        [self update:0];
    }
    

    It will crash on that release if the target is junk and not nil. Sending a message to nil is fine, but not to some arbitrary junk memory. That gives me a EXC_BAD_ACCESS.

提交回复
热议问题