有人可以帮助我回答以下3个问题吗?它将帮助我解决我的问题。
int
中声明app delegate
。int
值传输到其他类。NSLog
此值。 答案 0 :(得分:3)
// AppDelegate.h
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic) int myIntVariable;
@end
// ViewController.m
#import "AppDelegate.h"
- (void)viewDidLoad {
[super viewDidLoad];
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
delegate.myIntVariable = 4;
NSLog(@"%d", delegate.myIntVariable);
}
答案 1 :(得分:0)
在AppDelegate.h中声明int属性,就像在任何其他类中一样:
@property (nonatomic) int randomNumber;
然后在您想要访问此变量的类中导入AppDelegate.h。
并写下以下内容:
AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSLog(@"Int: %d", delegate.randomNumber);
答案 2 :(得分:-2)
在AppDelegate.h或swift中创建静态变量。我迅速做了这个答案。
static var myInt = 2
然后在ViewController或其他类上访问它。
override func viewDidLoad() {
super.viewDidLoad()
println(AppDelegate.myInt)
}
您可以执行实例变量,但如果您这样做:
var myInt = 2
然后你需要AppDelegate的一个对象来获取值:
println(AppDelegate().myInt)
我更喜欢第一个,因为我不必创建对象,但这里AppDelegate是一个单身,所以无论哪种方式都很好。