GKSession displayNameForPeer阻止释放会话(iOS 4.0,4.1)

时间:2011-05-28 16:29:24

标签: ios gamekit gksession

在为另一个对等方(而非自己)调用displayNameForPeer之后释放GKSession时,我可以可靠地使模拟器崩溃,我不确定这是否是我做错了或者它是Apple的Gamekit框架的错误(以及我是否需要担心它,因为我只看到4.0和4.1下的崩溃,而不是4.2 +)。

输出结果为:

found available peer; checking name and ID... m4, 26176566
*** -[GKSessionInternal lock]: message sent to deallocated instance 0x7508900

这是最小的可重现代码集 - 请注意,另一个GKSession必须在网络上可见(以便找到可用的对等方来调用displayNameForPeer)来触发崩溃。

在另一台设备上运行相同的代码但没有makeUnavailable和killSession调用
- (void)viewDidLoad
{

[self createSession];
[self makeAvailable];

peerListAvailable = [[NSMutableArray alloc] initWithArray:[currentSession peersWithConnectionState:GKPeerStateAvailable]];
for (NSString *peer in peerListAvailable)
{
    // this method guarantees the crash on session release
    NSLog(@"found available peer; checking name and ID... %@, %@",[currentSession displayNameForPeer:peer], peer);
}
[peerListAvailable release];
peerListAvailable = nil;


[self makeUnavailable];
[self killSession];

[super viewDidLoad];
}


- (void) createSession
{
if (!currentSession)
{
    currentSession = [[GKSession alloc] initWithSessionID:@"GKTester" displayName:nil sessionMode:GKSessionModePeer];
    currentSession.delegate = self;
    currentSession.disconnectTimeout = 30;
    [currentSession setDataReceiveHandler: self withContext:nil];
}

}

-(void) killSession
{
if (currentSession) 
{
    [currentSession disconnectFromAllPeers];
    [currentSession setDelegate:nil];
    [currentSession setDataReceiveHandler:nil withContext:nil];
    [currentSession release]; // crash occurs after this
    currentSession = nil;   
}
}

-(void) makeAvailable
{
while (currentSession && !currentSession.available)
{
    [currentSession setAvailable:YES];
    [NSThread sleepForTimeInterval:.5];
}
}

-(void) makeUnavailable
{
while (currentSession && currentSession.available)
{
    [NSThread sleepForTimeInterval:.5];
    [currentSession setAvailable:NO];
}

}

1 个答案:

答案 0 :(得分:0)

您的代码中有一个过度发布:

[currentSession disconnectFromAllPeers];
[currentSession setDelegate:nil];
[currentSession setDataReceiveHandler:nil withContext:nil];
[currentSession release]; // This is an over-release
currentSession = nil; // You are trying to access a variable after it's been released

您应该仅在dealloc中释放currentSession成员变量,如下所示:

- (void)dealloc
{
    [currentSession release];
    [super dealloc];
}