我使用 ARC 为 iOS 6.1 编写代码,但我遇到的问题是 nsmutablearray 中的对象“丢失”了。我将更详细地解释它:
- 有一个父视图,它有一个 NSMutableArray 应该保存一些对象(地址)
- 每次我点击按钮时,数组的数据都会用 NSLog 显示,然后导航控制器推送到 ChildView
- childview 生成一个新的地址对象
如果我这样做然后按下视图中的后退按钮并想尝试相同的情况(再次按下按钮),则数组中的数据将丢失并且我得到一个 EXC_BAD_ACCESS
我的假设:当我回到 parentView 时,ARC 会释放第二个视图及其中的所有内容。但是我的地址对象将从数组中引用,因此该对象的 ARC 计数器不应为 0。
谁能帮我?这是具体的代码
父视图控制器 h:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (nonatomic, strong) NSMutableArray *adresses;
@property int count;
-(void)goFurther;
@end
ParentViews 控制器 m:
#import "ViewController.h"
#import "SecondViewController.h"
#import "Address.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
self.title=@"First View";
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Add address" style:UIBarButtonItemStylePlain
target:self action:@selector(goFurther)];
[self.navigationItem setLeftBarButtonItem:addButton];
self.adresses=[[NSMutableArray alloc] init];
self.count=0;
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) goFurther{
for (Address *a in self.adresses) {
NSLog(@"Adresse:");
NSLog(a.street);
NSLog(a.door);
}
self.count++;
SecondViewController *second=[[SecondViewController alloc]initWithView:self];
[self.navigationController pushViewController:second animated:true];
}
@end
ChildViews 控制器 h:
#import <UIKit/UIKit.h>
#import "ViewController.h"
@interface SecondViewController : UIViewController
@property ViewController * viewCon;
-(id) initWithView: (ViewController*) view;
@end
ChildViews 控制器 m:
#import "SecondViewController.h"
#import "Address.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(id) initWithView: (ViewController*) view{
self = [super init];
self.viewCon=view;
Address *a=[Address alloc];
a.street=[NSString stringWithFormat:@"Street %d", self.viewCon.count];
a.door=@"Door";
[self.viewCon.adresses addObject: a];
return self;
}
- (void)viewDidLoad
{
self.title=@"Second View";
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end