我在这个link中尝试了Moshe的代码,除了“for(UIButton *按钮在...中”的部分之外它有效,每当我点击一个按钮时它都会崩溃。
所以我在viewDidLoad方法中尝试了这段代码:
UIButton *testButton = [[UIButton alloc]initWithFrame:CGRectMake(20,50,30,30)];
testButton.backgroundColor = [UIColor orangeColor];
[testButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[testButton setTitle:@"A" forState:UIControlStateNormal];
[testButton addTarget:self action:@selector(commonMethodForButtons:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:testButton];
[testButton release];
我的项目除了这个和Moshe的示例代码之外什么都没有。知道应用程序崩溃的原因吗?我没有崩溃日志。
编辑:
在开放范围我有这个方法:
-(void)commonMethodForButtons:(id)sender
{
NSLog (@"you touched me!");
}
编辑2:
我找到了这个问题的原因:
我在AppDelegate中注释掉了[mvc release];
,所以它现在完美地工作了:)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
MVC *mcv = [[MVC alloc]initWithNibName:nil bundle:nil];
[self.window addSubview: mcv.view];
//[mcv release];
[self.window makeKeyAndVisible];
return YES;
}
感谢您指出这一点! :)
答案 0 :(得分:1)
使用mcv作为属性
在AppDelegate的头文件中:
@class MVC;
@interface AppDelegate : UIResponder {
MVC *mcv;
}
@property (nonatomic, retain) MVC *mcv;
在实施档案
中@implementation AppDelegate
@synthesize mcv;
- (void)dealloc
{
[mcv release];
[super dealloc];
}
答案 1 :(得分:0)
不,你应该不通过评论[mcv release]
来解决你的问题(这只是修复一个症状,而不是问题,如果你转换为ARC会导致问题,您应该),也不应该像在当前接受的答案中那样存储mcv
(不应该是mvc
?)作为应用代表的ivar但是(a)未能设置rootViewController
但是(b)仍在使用addSubview
。您应该使用应用委托的rootViewController
。当前解决方案不会正确配置视图控制器层次结构。它应该如下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
MVC *mvc = [[MVC alloc]initWithNibName:nil bundle:nil]; // really no NIB name?!?
//[self.window addSubview: mvc.view];
self.window.rootViewController = mvc;
[mvc release];
[self.window makeKeyAndVisible];
return YES;
}
或者,更好的是,符合非ARC Xcode模板生成的标准didFinishLaunchingWithOptions
,例如:
// AppDelegate.h
#import <UIKit/UIKit.h>
@class ViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ViewController *viewController;
@end
和
// AppDelegate.m
#import "AppDelegate.h"
#import "MVC.h"
@implementation AppDelegate
@synthesize window = _window;
@synthesize viewController = _viewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.viewController = [[MVC alloc]initWithNibName:nil bundle:nil]; // really no NIB name?!?
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
我从来没有引用过这个viewController
属性,但鉴于这是Xcode生成的默认代码,我认为这是一个很好的做法。