我很难理解父母和孩子是如何沟通的(以及他们如何相互传递数据)。我有两个简单的对象(两个ViewControllers)。我理解父-子关系应该允许我使用属性将两个变量从子对象传递到父对象。因为我包括了Obj。B进入Obj A,我假设A是父母,B是孩子。我也知道孩子知道父母,反之亦然,对吗?
我也包括了。B转入Obj。A和我希望能够访问我在Obj的头文件中声明的几个变量。B
谁能给我一个简单的例子,帮助我结束我的困惑?非常感谢。
发布于 2013-11-01 12:50:13
要将数据(对象或值)从推送或表示ViewControllerB的ViewControllerA转发到ViewControllers,您需要执行如下操作:
(例如,将NSString从ViewControllerA传递给ViewControllerB )
在没有存储板的情况下向前传递数据:
ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
viewControllerB.aString = myString; // myString is the data you want to pass
[self presentViewController:viewControllerB animated:YES completion:nil];使用UINavigationController:
ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
viewControllerB.aString = myString;
[self.navigationController pushViewController:viewControllerB animated:YES];在viewControllerB内部,您需要在.h上有一个@property,例如:
@property (nonatomic, strong) NSString *aString;在您的.m中,您可以检索这个@property:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"%@", _aString);
}这是一个使用NSString的示例,但是您可以传递任何对象。
发布于 2013-10-31 18:24:18
我觉得你倒过来了。父母应该知道孩子的事。孩子不需要知道父母的情况。
父级可以强烈引用其子级。(X)
//inside the parent class
@property (nonatomic, strong) id childObject;子对象通常不会清楚地知道它的“父”是什么,但是它对委托的引用会很弱。该委托可以是特定类型的类,也可以是符合特定协议的类型id的泛型类。(X)
//inside the child class
@property (nonatomic, weak) id<SomeProtocol> delegate;发布于 2013-10-31 16:15:27
可以在其中一个对象中使用弱赋值设置循环引用:
ObjectA.h
@class ObjectB
@interface ObjectA
@property (strong) ObjectB *parent;
@endObjectA.m
#import "ObjectA.h"
#import "ObjectB.h"
@implementation ObjectA
// methods
@endObjectB.h
@class ObjectA
@interface ObjectB
@property (weak) ObjectA *child;
@endObjectB.m
#import "ObjectB.h"
#import "ObjectA.h"
@implementation ObjectB
// methods
@endhttps://stackoverflow.com/questions/19711468
复制相似问题