何时释放添加到NSMutableDictionary的对象

Ben*_*ney 2 arrays iphone dictionary memory-leaks iphone-sdk-3.1

我正在开发一个iPhone应用程序,它将在运行时构造一个NSMutableDictionary,其值(键值对)将是NSMutableArrays.作为Objective-C的新手,我担心以下会导致内存泄漏:

- (void) addNewSupplierPhoto:(UIImage*)image toSupplierID:(NSInteger*) supplierID{
NSMutableArray* supplierPhotoArray = [supplierPhotos objectForKey:supplierID];
if(supplierPhotoArray == nil)
{
    supplierPhotoArray = [[NSMutableArray alloc] init];
    [supplierPhotos setObject:supplierPhotoArray forKey:supplierID];
    [supplierPhotoArray release];
}
}
Run Code Online (Sandbox Code Playgroud)

supplierPhotos是一个NSMutableDictionary,它是包含类的成员变量.

如您所见,当我接受新的UIImage*放入结构时,我首先检查对应于第二个参数(supplierID)的键值对的对象是否为nil.如果它是nil,我分配一个新的NSMutableArray并将其设置为该键的对象,然后释放它.假设我在包含此方法的类的dealloc中释放NSMutableDictionary,是否会释放引用?在释放NSMutableDictionary之前,我是否需要运行它并释放包含在其中的各个NSMutableArrays?

谢谢,

本B.

小智 5

当您将对象添加到像字典或数组这样的容器中时,将自动调用retain,当您将容器作为问题释放容器时,它将调用每个对象的"释放"来释放对象的内存.