天兒真好所有創建的對象,的iOS:可以在一個視圖中看到在另一個
我一直在閱讀有關的協議和委託的控制器之間傳遞數據。
假設ViewControllerA的對象上創建一個實例:
myObject = [[anObject alloc]init];
[myObject setProperty: value];
如何ViewControllerB訪問myObject的財產? ViewControllerB如何知道由ViewControllerA創建的對象?
感謝,
天兒真好所有創建的對象,的iOS:可以在一個視圖中看到在另一個
我一直在閱讀有關的協議和委託的控制器之間傳遞數據。
假設ViewControllerA的對象上創建一個實例:
myObject = [[anObject alloc]init];
[myObject setProperty: value];
如何ViewControllerB訪問myObject的財產? ViewControllerB如何知道由ViewControllerA創建的對象?
感謝,
您可以使用NSNotificationCenter
讓任何有興趣瞭解新對象的人知道。
通常這是在模型層完成的,例如我有一個Person
對象。
在Person
.h文件中
extern NSString *const NewPersonCreatedNotification;
在.m文件
3210定義一個「新的人創建的通知」當創建一個人(在init方法)發佈通知
[[NSNotificationCenter defaultCenter] postNotificationName:NewPersonCreatedNotification
object:self
userInfo:nil];
然後,任何想知道創建新人的人都需要觀察此通知,例如ViewCont rollerA想知道,所以在它的init方法中,我這樣做:
- (id)init
{
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleNewPersonCreatedNotification:)
name:NewPersonCreatedNotification
object:nil];
}
return self;
}
- (void)handleNewPersonCreatedNotification:(NSNotification *)not
{
// get the new Person object
Person *newPerson = [not object];
// do something with it...
}
謝謝Eyal。我會通知一些作業。 – 2012-08-05 00:09:22
如果B來到後A(即它們是分層)你可以傳遞對象,以B(創建後或在prepareForSegue
:
bController.objectProperty = myObject;
如果兩者都爲活動用戶在同一時間(通過標籤欄),你可以使用通知,這是不同於代表的關係是鬆散的 - 發送對象不必知道接收對象的任何內容。
// in A
[[NSNotificationCenter defaultCenter]
postNotificationName:ObjectChangedNOtificationName
object:self
userInfo:dictionaryWithObject];
// in B
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(objectChanged:)
name:ObjectChangedNOtificationName
object:nil];
感謝蒙迪。我會看看通知。 – 2012-08-05 00:10:03
ViewControllerB可以是ViewControllerA的委託。這樣ViewControllerA可以在創建對象時將消息傳遞給ViewControllerB。 – jtomschroeder 2012-08-04 23:18:07