我存档了实现的自定义对象数组(NSMutableArray)。
一旦我将其从文件加载到保留属性
@属性(非原子的,保留)NSMutableArray *伙伴;
该对象的释放计数为2(正确,它是自动释放的1 +保留的属性的1),但是没有人释放它,保留计数变为1,所以当我释放它时,我得到
-[__ NSArrayM keepCount]:发送到已释放实例的消息
(我认为因为1保留计数是自动释放)
这是完整的代码:
BuddieListViewController.h
#import <UIKit/UIKit.h>
#import "Buddie.h"
@interface BuddieListViewController : UITableViewController {
IBOutlet NSMutableArray *buddies;
[...]
}
[...]
@property (nonatomic, retain) NSMutableArray *buddies;
[...]
@end
BuddieListViewController.m
#import "BuddieListViewController.h"
#import "Buddie.h"
#import "PreviewViewController.h"
@implementation BuddieListViewController
@synthesize buddies;
[...]
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
[self loadFromDisk];
}
return self;
}
- (void)loadFromDisk {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *appFile = [documentsPath stringByAppendingPathComponent:@"BuddieArchive.ark"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:appFile]) {
self.buddies = [NSKeyedUnarchiver unarchiveObjectWithFile:appFile];
NSLog(@"1- buddies retain count %d (should be 2, 1 + 1autorelease)", [buddies retainCount]);
} else {
self.buddies = [NSMutableArray arrayWithCapacity:1];
}
}
[...]
- (IBAction)cancelledBuddie:(NSNotification *)notification
{
[editingBuddie release];
NSLog(@"2- buddies retain count %d (should be 2, 1 + 1autorelease)", [buddies retainCount]);
[buddies release];
[self loadFromDisk];
[self.tableView reloadData];
}
有谁知道为什么会这样吗?
最佳答案
如果需要使数组无效,请使用属性访问器将其设置为nil
:
self.buddies = nil;
综合实现解决了内存管理问题。尽量避免将
-retain/-release
消息直接发送到实例变量,而应让属性访问器为您处理事情。它将为您省去很多麻烦。关于ios - iPhone NSMutableArray和NSKeyedUnarchiver unarchiveObjectWithFile发布奇怪,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3885368/