我有一些目标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