0

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...!

Kostas
  • 1,504
  • 1
  • 11
  • 13

1 Answers1

0

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;
} 
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
  • Dave first of all thanks for your help. The statement to make a copy of a GKSession object using the copyWithZone is the following : myViewController.currentSession=[self copy]; Am i right? – Kostas May 01 '12 at 19:52