視圖控制器之間要交換資料,依場景不同有幾種常用手段。下面整理三種最典型的寫法。
如果只是傳一個 float、一個字串這類零碎值,用 NSUserDefaults 最省事。
寫入端:
[[NSUserDefaults standardUserDefaults] setFloat:value forKey:@"float"];
讀取端:
[[NSUserDefaults standardUserDefaults] floatForKey:@"float"];
要注意的是,NSUserDefaults 本質上是 plist 持久化,並不適合傳遞大量資料或暫時性的狀態,用錯地方會拖慢效能。
當你希望「事件發生的地方」和「處理事件的地方」彼此不需要知道對方存在時,通知是最自然的選擇。以一個繪圖元件回傳觸控終點為例:
發送端:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
CGRect roundRect = [self rectNeedRefreshFromThisPoint:point];
mLastPoint = CGPointMake(-1, -1);
[self addToCurrentLineWithPoint:point.x y:point.y];
[self endLine];
[self setNeedsDisplayInRect:roundRect];
NSNumber *pointX = [NSNumber numberWithFloat:point.x];
NSNumber *pointY = [NSNumber numberWithFloat:point.y];
NSDictionary *pointDict = [NSDictionary dictionaryWithObjectsAndKeys:
pointX, @"pointX", pointY, @"pointY", nil];
[[NSNotificationCenter defaultCenter]
postNotificationName:@"passTouchedEndPointMsg"
object:self
userInfo:pointDict];
}
接收端:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(getTouchedPoint:)
name:@"passTouchedEndPointMsg"
object:nil];
- (void)getTouchedPoint:(NSNotification *)noti
{
NSDictionary *pointDict = [noti userInfo];
touchedEndPointX = [[pointDict objectForKey:@"pointX"] floatValue];
touchedEndPointY = [[pointDict objectForKey:@"pointY"] floatValue;
NSLog(@"%f:%f", touchedEndPointX, touchedEndPointY);
}
幾個關鍵觀念:
postNotificationName 的 object 參數代表「通知的發送者」,接收端可以用它做過濾;真正要傳的資料必須放進 userInfo,而且型別只能是 NSDictionary;接收端則用 [notification userInfo] 把字典取出來。
另外提醒一個實務上的重點:addObserver 之後記得在 dealloc 或合適的時機呼叫 removeObserver,否則容易出現野指標崩潰。
如果兩個 ViewController 之間有明確的父子或引用關係,最簡單的其實就是在目標控制器宣告一個屬性,跳轉前把值指派進去。這也是 Storyboard 的 prepareForSegue 在做的事情。通知與 NSUserDefaults 更適合處理「關係鬆散」或「全域狀態」的場景,不要拿來取代最樸素的屬性傳值。