我正在用Xcode做一个应用程序,遇到了一些问题。我正在使用GameKit框架来支持两个iOS设备之间的蓝牙通信。应用程序被设置为其中一个设备是“主”设备,另一个是“从”设备,根据从“主”设备接收的数据更改其屏幕内容。用户可以选择是主设备还是从设备,当做出选择时,另一个设备自动成为相反的角色。这些都是在一个视图控制器类中完成的。选择角色后,将向baseViewController添加一个子视图。
我的问题是,当添加了子视图时,我希望能够使用baseViewController类中的方法发送数据。使用当前设置时,调用操作becomeMaster:sender的设备会崩溃。
到目前为止,我尝试过的是,
BaseViewController:
-(IBAction)becomeMaster:(id)sender {
[self dataToSend:@"slave"]; //tells peer device to become slave, since this device is master
masterViewController = [[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil];
[masterViewController setBaseViewController:self];
[self.view addSubview:masterViewController.view];
}
-(void)dataToSend:(NSString *)direction {
//—-convert an NSString object to NSData—-
NSData* data;
NSString *str = [NSString stringWithString:direction];
data = [str dataUsingEncoding: NSASCIIStringEncoding];
[self mySendDataToPeers:data];
}
-(void)dataToSend:(NSString *)direction {
//—-convert an NSString object to NSData—-
NSData* data;
NSString *str = [NSString stringWithString:direction];
data = [str dataUsingEncoding: NSASCIIStringEncoding];
[self mySendDataToPeers:data];
}
//----------------------------------------------------------------------------//
- (void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context {
//—-convert the NSData to NSString—-
NSString* str;
str = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
[self useReceivedData:str];
[str release];
}
-(void)useReceivedData:(NSString *)str {
if ([str isEqualToString:@"forward"]) {
[slaveViewController.view setBackgroundColor:[UIColor blackColor]];
}
}MasterViewController:
-(void)setBaseViewController:(BaseViewController *)bvc {
baseViewController = bvc;
}
-(IBAction)goForward:(id)sender {
actionLabel.text = @"goingForward";
[baseViewController dataToSend:@"forward"];
}其中大部分代码是标准Apple文档/示例的一部分,但我将其包含进来是为了理解逻辑流程。
我认为问题源于becomeMaster:sender和setBaseViewController:bvc方法。有人能帮我修一下吗?非常感谢!
发布于 2011-03-28 12:40:10
你会遇到什么样的崩溃?EXC_BAD_ACCESS?尝试在可执行文件的参数中启用NSZombieEnabled。很难说是什么原因导致了崩溃,但您可以尝试将您的setBaseViewController:实现改为:
-(void)setBaseViewController:(BaseViewController *)bvc {
[self willChangeValueForKey:@"baseViewController"];
[baseViewController autorelease]
baseViewController = [bvc retain];
[self didChangeValueForKey:@"baseViewController"];
}并将[baseViewController release];添加到MasterViewController的-dealloc方法中。
请记住,没有必要为baseViewController提供自定义设置器。如果您的头文件中有以下属性声明:
@property (nonatomic, retain) BaseViewController *baseViewController;使用@synthesize baseViewController时,已经为您生成了-setBaseViewController:方法,并内置了键值观察支持。如果您不熟悉Objective-C2.0属性,我建议您阅读Apple's documentation。
https://stackoverflow.com/questions/5453888
复制相似问题