Why does this create a memory leak (iPhone)?

前端 未结 6 2051
暖寄归人
暖寄归人 2020-12-10 16:06
//creates memory leak
  self.editMyObject = [[MyObject alloc] init];

//does not create memory leak
  MyObject *temp = [[MyObject alloc] init];
  self.editMyObject =         


        
6条回答
  •  孤街浪徒
    2020-12-10 16:32

    Everyone else has already covered why it causes a memory leak, so I'll just chime in with how to avoid the 'temp' variable and still prevent a memory leak:

    self.editMyObject = [[[MyObject alloc] init] autorelease];
    

    This will leave your (retain) property as the sole owner of the new object. Exactly the same result as your second example, but without the temporary object.

提交回复
热议问题