在 MVC 架構下,單例是實現「非父子關係」視圖控制器間數據共享的經典方案。本文通過一個完整的 DataModel 單例,演示如何安全地存取與傳遞數據。
@interface DataModel : NSObject
// 需共享的數據屬性
@property (strong, nonatomic) NSString *userName;
@property (strong, nonatomic) NSNumber *userAge;
// 單例訪問入口
+ (instancetype)sharedInstance;
@end
@implementation DataModel
+ (instancetype)sharedInstance {
static DataModel *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
// 可選:提供便利方法更新數據
- (void)updateUserInfoWithName:(NSString *)name age:(NSNumber *)age {
self.userName = name;
self.userAge = age;
}
@end
- (void)saveUserInput {
[[DataModel sharedInstance] updateUserInfoWithName:@"張三" age:@(25)];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
DataModel *model = [DataModel sharedInstance];
self.nameLabel.text = model.userName;
self.ageLabel.text = [model.userAge stringValue];
}
dispatch_once 保證單例創建的原子性。NSNumber/NSValue 存儲。單例雖便利,但濫用會導致隱式依賴難以測試,建議僅用於真正的「全局唯一狀態」。