【发布时间】:2011-04-03 20:22:09
【问题描述】:
我目前正在为 iPhone 构建一个应用程序,但无法弄清楚为什么我总是在 Leaks Instrument 工具中出现内存泄漏。
这是代码,我已将 cmets 添加到它发生的两个地方。
NSString *pathname = [[NSBundle mainBundle] pathForResource:self.toUseFile ofType:@"txt" inDirectory:@"/"];
//Line below causes a leak
self.rawCrayons = [[NSString stringWithContentsOfFile:pathname encoding:NSUTF8StringEncoding error:nil] componentsSeparatedByString:@"\n"];
self.sectionArray = [NSMutableArray array];
for (int i = 0; i < 26; i++) [self.sectionArray addObject:[NSMutableArray array]];
for(int i=0; i<self.rawCrayons.count; i++)
{
self.string = [self.rawCrayons objectAtIndex:i];
NSUInteger firstLetter = [ALPHA rangeOfString:[string substringToIndex:1]].location;
if (firstLetter != NSNotFound)
{
NSInteger audio = AUDIONUM(self.string);
NSInteger pictures = PICTURESNUM(self.string);
NSInteger videos = VIDEOSNUM(self.string);
//Line below causes a leak
[[self.sectionArray objectAtIndex:firstLetter] addObject:[[Term alloc] initToCall:NAME(self.string):audio:pictures:videos]];
}
[self.string release];
}
提前致谢!
编辑
这是我的财产声明。
@property (nonatomic, retain) NSArray *filteredArray;
@property (nonatomic, retain) NSMutableArray *sectionArray;
@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, retain) UISearchDisplayController *searchDC;
@property (nonatomic, retain) NSString *toUseFile;
@property (nonatomic, retain) NSArray *rawCrayons;
@property (nonatomic, retain) NSString *string;
@property (nonatomic, retain) TermViewController *childController;
以下是在遵循 Nick Weaver 的修复程序后发生的泄漏。
这里是 NSCFString 之一的扩展版本。
还有一张图片。
负责来电者的图片:
另外,因为这可能有用,这里是 Term 的属性:
@property (nonatomic, retain) NSString *name;
@property (nonatomic) NSInteger numberAudio;
@property (nonatomic) NSInteger numberPictures;
@property (nonatomic) NSInteger numberVideos;
以及实现:
@implementation Term
@synthesize name, numberAudio, numberPictures, numberVideos;
- (Term*)initToCall:(NSString*) toSetName:(NSInteger) audio:(NSInteger) pictures:(NSInteger) videos
{
self.name = [toSetName retain];
self.numberAudio = audio;
self.numberPictures = pictures;
self.numberVideos = videos;
return self;
}
- (NSString*)getName
{
return [[name retain] autorelease];
}
-(void)dealloc
{
[name release];
[super dealloc];
}
@end
【问题讨论】:
-
了解
rawCrayons属性的定义方式可能会有所帮助。 -
@Jim Blackler 它在我发布的代码中,不是吗?
-
我的意思是头文件中的定义,例如
@property (nonatomic, retain) IBOutlet NSButton *myButton; -
@Jim Blackler 我在上面添加了我的属性声明。
标签: iphone string memory-leaks autorelease