天儿真好所有创建的对象,的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