在iOS中傳值的方式有很多種方式澈吨,有最普遍的就是屬性傳值,代理傳值闻坚,block傳值等方式了。
寫了OC和swift的兩個(gè)版本的傳值demo兢孝。
其中需要說明一下的是窿凤,這個(gè)通知傳值。
在通知傳值的時(shí)候跨蟹,有的時(shí)候會(huì)出現(xiàn)如下的問題雳殊,也就是當(dāng)通知中心發(fā)出了通知,接收通知的一方卻沒有收到任何消息窗轩。這可能是線程阻塞的原因夯秃,只需要將通知中心放在子線程中去處理。
// OC
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:self userInfo:@{@"text" : @"請(qǐng)輸入賬號(hào)名"}];
}];
// swift
OperationQueue.main.addOperation {
let cell = self.tableView.cellForRow(at: IndexPath(row: 4, section: 0))
let wjNotificationName = Notification.Name.init(rawValue: "notificationTest")
NotificationCenter.default.post(name: wjNotificationName, object: self, userInfo: ["text" : cell?.textLabel?.text ?? "沒有值傳入"])
}
單例傳值:
在OC和swift中創(chuàng)建單例傳值痢艺,一般都會(huì)創(chuàng)建一個(gè)單例類仓洼,通過這個(gè)單例類來中轉(zhuǎn),進(jìn)行傳值堤舒,也就是說這個(gè)單例類就像是個(gè)容器一樣進(jìn)行存儲(chǔ)數(shù)據(jù)色建,也就是說正向反向傳值都可以。
但是在OC中和swift中創(chuàng)建單例類還是有些不同:
// OC采用的是GCD或者是其他的方法進(jìn)行創(chuàng)建
+ (wjSingleTon *)shareSingleTon {
static wjSingleTon *singleTon = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
singleTon = [[self alloc] init];
});
return singleTon;
}
// swift創(chuàng)建單例類
// MARK:- 單例類
final class wjSingleTon: NSObject {
static let sharedInstance = wjSingleTon()
var text : String!
override init() {}
}
其他的傳值方式在oc和swift中沒有多大的差別舌缤。