Copy of GKSession object implementing copyWithZone

130 Views Asked by At

I want to make a copy of a GKSession object and I implement copyWithZone as follow :

-(id)copyWithZone:(NSZone *)zone {

GKSession *kati = [[GKSession allocWithZone: zone] init];
kati=_currentSession;    
return kati;}    

Nevertheless I don't take a copy of the initial object but a reference to that.

Am I missing something...;

The implementation of the copyWithZone is the way to make a copy of a GKSession object, or not?

Thanks in advance...!

1

There are 1 best solutions below

1
On

Let's take a look at what your code is doing:

GKSession *kati = [[GKSession allocWithZone: zone] init];

You allocate a new GKSession object, and update the kati variable to point to the object.

kati=_currentSession;  

You change the kati variable to point to another object. This means the object you just allocated is leaked; you don't have a pointer to it anymore, but it wasn't ever deallocated.

return kati;

You return the value of the kati variable, which is a pointer to the _currentSession object.

This is clearly not what you want. You want to create a new GKSession with the same underlying information as _currentSession, right? In that case, I would start with:

- (id)copyWithZone:(NSZone *)zone {
  NSString *sessionID = [_currentSession sessionID];
  NSString *name = [_currentSession displayName];
  GKSessionMode sessionMode = [_currentSession sessionMode];
  GKSession *kati = [[GKSession alloc] initWithSessionID:sessionID displayName:name sessionMode:mode]; 
  return kati;
}