我是編程的小老弟,但我開始學習。我正在爲iPhone寫作,現在我陷入了這個問題。目標C:從多個外部類訪問同一班級的數據
我一直在嘗試在stackowerflow上找到答案,但是很難將這些信息與我自己的項目相關聯。
正如標題所述,我試圖通過其他「外部」類來訪問一個類的數據。我習慣於Java,但我知道這不會以同樣的方式工作。
如何從類中的文本字段保存字符串,以便稍後從其他類中檢索該字符串?
我在這裏本3類:
一個「模型」級以保存字符串數據 一個「視圖 - 控制器」級以保存TextField的字符串中的「模式」級 一
#import <Foundation/Foundation.h>
@interface Model : NSObject
- (void)setPlayerOneName:(NSString *)tfString;
- (NSString *)getPlayerOne;
@end
model.m:
「記分牌」 級從 「模型」 級第一model.h提取數據
目前,class.h保存字符串中的 「型號」 級:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
.M:
#import "ViewController.h"
#import "Model.h"
#import "ScoreBoard.h"
@interface ViewController()
@property (strong) Model *model;
@end
@implementation Whist_CalculatorViewController
- (void)textFieldDidEndEditing:(UITextField *)textField{
[self.model setPlayerOneName:textField.text];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"saveAndStart"]){
NSLog(@"prepareForSegue: %@", segue.identifier);
[segue.destinationViewController updateThatScoreBoard];
}
}
@end
最後記分牌類,至極訪問模型名稱字符串: ScoreBoard.h:
#import <UIKit/UIKit.h>
@interface ScoreBoard : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *player1Label;
- (void)updateThatScoreBoard;
@end
和ScoreBoard.m:
#import "ScoreBoard.h"
#import "Model.h"
@interface ScoreBoard()
@property (strong) Model *model;
@end
@implementation ScoreBoard
@synthesize player1Label = _player1Label;
@synthesize model = _model;
- (void)updateThatScoreBoard{
[self.player1Label setText:[self.model getPlayerOne]];
}
- (void)viewDidLoad{
[self updateThatScoreBoard];
}
- (void)viewDidUnload {
[self setPlayer1Label:nil];
[super viewDidUnload];
}
@end
任何輸入是非常感謝!
非常感謝您的回答:)我仍然不知道如何從「同一獲取數據「模型實例。如果我在一個類中創建模型並存儲數據,但是需要從另一個類中收集數據,然後再次創建模型 - 那麼它將成爲一個新的空模型? – NooberMan 2012-02-27 19:01:20
我編輯了我的答案。我希望它對你有所幫助 – GeT 2012-02-27 19:17:36
所有這些看起來都很棒,但有兩點:1,「#pragma mark - 」是什麼意思? 2,我的xcode似乎不喜歡「靜態模型oneAndOnlyInstance;」我不知道它做了什麼。但除此之外,這看起來像是一個偉大的解決我的問題 – NooberMan 2012-02-27 19:43:39