我寫了下面的代碼保存在另一類別後訪問類變量:問題從另一個類訪問變量
SettingsController.h
@interface SettingsController : NSObject
@property (nonatomic) BOOL isHighway;
@property (nonatomic) BOOL isToll;
@property (nonatomic) BOOL isVoiceNavigation;
@property (nonatomic) BOOL isVoiceCommand;
-(id)initWithHighway:(BOOL)_isHighway;
-(id)initWithToll:(BOOL)_isToll;
-(id)initWithVoiceNavigation:(BOOL)_isVoiceNavigation;
-(id)initWithVoiceCommand:(BOOL)_isVoiceCommand;
-(BOOL)isHighwayOn;
-(BOOL)isTollOn;
-(BOOL)isVoiceNavigationOn;
-(BOOL)isVoiceCommandOn;
@end
SettingsController.m
@implementation SettingsController
@synthesize isHighway,isToll,isVoiceNavigation,isVoiceCommand;
-(id)initWithHighway:(BOOL)_isHighway{
if ((self = [super init])) {
self.isHighway = _isHighway;
}
return self;
}
-(id)initWithToll:(BOOL)_isToll{
if ((self = [super init])) {
self.isToll = _isToll;
}
return self;
}
-(id)initWithVoiceNavigation:(BOOL)_isVoiceNavigation{
if ((self = [super init])) {
self.isVoiceNavigation = _isVoiceNavigation;
}
return self;
}
-(id)initWithVoiceCommand:(BOOL)_isVoiceCommand{
if ((self = [super init])) {
self.isVoiceCommand = _isVoiceCommand;
}
return self;
}
-(BOOL)isHighwayOn{
return self.isHighway;
}
-(BOOL)isTollOn{
return self.isToll;
}
-(BOOL)isVoiceNavigationOn{
return self.isVoiceNavigation;
}
-(BOOL)isVoiceCommandOn{
return self.isVoiceCommand;
}
@end
從我的SettingsViewController類,我初始化值如下:
SettingsController *settingsController = [[SettingsController alloc] initWithHighway:isHighways];
,並訪問他們作爲
BOOL isHighway = [settingsController isHighwayOn];
但是,如果我試圖從另一個類訪問這些變量,RouteViewController如下:
SettingsController *settingsController = [[SettingsController alloc] init];
BOOL isHighway = [settingsController isHighwayOn];
它總是給我0
,我從來沒有得到1
。
任何人都可以請幫助我訪問這些變量?
編輯
OK,我已經去除了SettingsController
,並採取其接口爲RouteViewController
。我是從SettingsViewController
初始化如下:
RouteViewController *routeController = [[RouteViewController alloc] initWithHighway:isHighways];
然後通過簡單地從RouteViewController訪問它:
NSLog(@"Highway: %d",self.isHighway);
即使如此,它總是給我0
從未1
。
編輯
對於剛剛維持這4 UISwich在我SettingsViewController現在,我使用NSUserDefaults的。我認爲這是一個更好的方法...感謝所有的幫助...
你在哪裏設置的布爾值將價值?它們都從0開始,所以如果你沒有設置它們的值,當然,你會得到0而不是1. – ThomasM
我正在使用UISwitch切換布爾值 –
你的編輯不清楚。請更好地解釋您對代碼所做的更改,否則很難理解您放置代碼的位置以及代碼無法工作的原因。 – Saphrosit