我有一些目標C代碼來加載IKImageBrowserView上的圖像的這個問題。 我正在關注蘋果公司的圖片瀏覽器示例,但我仍然在某個時候失敗了,我猜測它的內存管理。 下面是一些代碼:目標C內存管理問題
/* Our datasource object */
@interface myImageObject : NSObject
{
NSString *_path;
}
@end
@implementation myImageObject
- (void)dealloc
{
[_path release];
[super dealloc];
}
/* our datasource object is just a filepath representation */
- (void)setPath:(NSString *)path
{
NSLog(@"setting path for %@",path);
if(_path != path)
{
[_path release];
_path = [path retain];
}
}
現在,看來我正確地保留對象中的路徑值。 現在到控制器代碼:
-(IBAction)loadMosaicImages:(id)sender
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *urls = [openFiles() retain];
NSInteger n;
n = [urls count];
NSURL *url = [urls objectAtIndex:0];
[self parsePathForImages:[url path]];
[urls release];
[pool drain];
}
- (void)updateDatasource
{
NSLog(@" UDS-> _importedImages length : %@",[_importedImages count]);
//-- update our datasource, add recently imported items
[_images addObjectsFromArray:_importedImages];
//-- empty our temporary array
[_importedImages removeAllObjects];
NSLog(@" UDS-> _images length : %@",[_images count]);
//-- reload the image browser and set needs display
[_imageBrowser reloadData];
}
-(void)parsePathForImages:(NSString *)path{
NSLog(@"Directory within thread method is %@",path);
NSArray *content = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
myImageObject *p;
for(int i=0;i<content.count;i++)
{
// NSLog(@"%@",(NSString *)[content objectAtIndex:i]);
NSLog(@"Complete : %@",[path stringByAppendingPathComponent:(NSString *)[content objectAtIndex:i]]);
/* add a path to our temporary array */
p = [[myImageObject alloc] init];
[p setPath:[path stringByAppendingPathComponent:[content objectAtIndex:i]]];
[_importedImages addObject:p];
[p release];
}
[self updateDatasource];
}
,這一切的相關代碼。 _images和_importedImages是NSMutableArrays在nib方法喚醒時被分配和插入的,openFiles()是一個靜態方法,它打開一個NSOpenpanel並返回一個NSArray路徑。
調試輸出這一做到這一點:
Directory within thread method is /Users/cromestant/Code/images/
Complete : /Users/cromestant/Code/images/1.jpg
setting path for /Users/cromestant/Code/images/1.jpg
Complete : /Users/cromestant/Code/images/2.jpg
setting path for /Users/cromestant/Code/images/2.jpg
Complete : /Users/cromestant/Code/images/3.jpg
setting path for /Users/cromestant/Code/images/3.jpg
。 。 。 然後在方法updateDataSource的第一行處停止崩潰,在NSLog上使用'EXEC_BAD_ACCESS'so'我在哪裏出錯內存管理? 我似乎正在創建一個autoreleasePool,所以我有時間保留其他地方,我釋放我的對象..我真的不知道問題出在哪裏。 在此先感謝。
順便說一下,我在文章中省略了所需的協議方法,因爲它們並不真正相關。 – cromestant