在多個畫面之間切換時,如何把資料從一個 View 傳到另一個 View,是 iOS 開發的基本功。以下整理三種常見的傳值方式,並附上範例。
這種方式只適合傳遞少量資料。例如要傳一個 float 值:
設定時:
[[NSUserDefaults standardUserDefaults] setFloat:fValue forKey:@"float"];
取值時:
[[NSUserDefaults standardUserDefaults] floatForKey:@"float"];
發送端在觸碰結束時,把座標打包成字典,透過通知中心拋出:
- (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);
NSLog(@"%s: point(%f,%f)", __FUNCTION__, point.x, point.y);
[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);
}
使用通知傳參數時有幾個重點:object 代表發送者;發送端可把要傳的參數放進 userInfo,且必須是 NSDictionary 類型;接收端則用 [notification userInfo] 取得這份字典。