0

我的问题是我想将对象从子视图(控制器)返回给父视图(控制器)。我通过这样的调用传递对象:

parentView.someObject=objectFromChild;

一切都很好,直到子视图被删除(因为它被弹出并且没有指针显示在上面)但是从子视图传递到父视图的对象也被删除。谁能告诉我如何保存我的对象(即使创建它的视图已被删除)?使用 NSString 我的方法效果很好......但是对于对象我总是得到 EXC_BAD_ACCESS

4

2 回答 2

0

确保父对象保留它。

于 2013-03-15T19:17:55.970 回答
0

Sounds like there are a couple of challenges here and I'll try to give some simple tips.

Passing Data
If you want to pass an object upward from a child to a parent, design your Child class so that the object or variable is a public property. Then, any other object (like Parent objects that own the Child) can access that property.

Keeping Data Alive
Usually EXC_BAD_ACCESS means the object has already been deleted by the system. Tell the system you want to hang on to the object by setting 'strong' in the property declaration, and this will take care of your EXC_BAD_ACCESS problem.

Take a look at the following code for an example of how to implement a very simple parent/child data relationship and retain data.

//****** Child.h

@interface Child : NSObject

// Child has a public property
// the 'strong' type qualifier will ensure it gets retained always
// It's public by default if you declare it in .h like so:
@property (strong, nonatomic) NSString *childString;

@end


//****** ParentViewController.h
#import <UIKit/UIKit.h>
#import "Child.h"

@interface ParentViewController : UIViewController

@property (strong, nonatomic) Child *myChild;

@end



//****** ParentViewController.m

@implementation ParentViewController

@synthesize myChild;

- (void)viewDidLoad {

    [super viewDidLoad];

    // create child object
    self.myChild = [[Child alloc] init];

    // set child object (from parent in this example)
    // You might do your owh setting in Child's init method
    self.myChild.childString = @"Hello";

    // you can access your childs public property
    NSLog(@"Child string = %@", self.myChild.childString;
}
于 2013-03-15T19:29:37.070 回答