iphone - iOS - 我很困惑这里是如何处理内存的?

标签 iphone objective-c ios ipad ios4

UIImage API 引用文档:-
initWithContentsOfFile:
使用指定文件的内容初始化并返回图像对象。

- (id)initWithContentsOfFile:(NSString *)path

参数
路径
文件的路径。此路径应包括标识图像数据类型的文件扩展名。
返回值 已初始化的 UIImage 对象,如果该方法无法找到文件或无法根据其内容初始化图像,则为nil


考虑到这种情况,假设我有一个类,它可以是任何类的扩展。就以UIImage为例。

@interface myImage : UIImage
{
    BOOL isDefaultSet;
}

-(id)initWithDefaultImage;

@end

@implementation myImage


-(id)initWithDefaultImage
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"someInvalidImage" ofType:@"png"];

    idDefaultSet = YES;

    return [self initWithContentsOfFile:path];
}

@end


//somewhere in other class:

NSString *path = [[NSBundle mainBundle] pathForResource:@"someInvalidImage" ofType:@"png"];

myImage *myObject = [[myImage alloc] initWithDefaultImage];
UIImage *yourObject = [[UIImage alloc] initWithContentsOfFile:path];

现在在这两种情况下,

“alloc”给出“retainCount+1”

如果

initWithDefaultImage/initWithContentsOfFile

由于某些问题返回 nil - 可以说(无效的文件路径),此内存将泄漏为

myObject/yourObject

即使分配是在init之前进行的,也会被设置为nil。

我见过许多以这种方式扩展类/接口(interface)的实现。我很困惑这里是如何处理内存的?任何人都可以分享对此的看法吗?

最佳答案

if [super init] returns nil, nil is returned. so the control returns from method and if (someInitializingFailed) block will never be executed and memory will be leaked as alloc is already executed before calling "initWithFoo"

如果 [super init] 返回 nil,super 的 init 已经自行清理并释放了 alloc< 分配的内存.

来自 Handling Initialization Failure :

You should call the release method on self only at the point of failure. If you get nil back from an invocation of the superclass’s initializer, you should not also call release.

关于iphone - iOS - 我很困惑这里是如何处理内存的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7569596/

相关文章:

iPhone:漫游 MCC

iphone - 如何在 iPhone 中使用 avFoundation 拍摄方形照片,就像在 Instagram 应用程序中一样?

ios - 谷歌地图 ios 中心的 Objective C 固定标记

iphone - 为什么使用 #define UIColor 作为 CGColorRef 会导致崩溃?

ios - NSDictionary 和 UITableView 副标题

ios - iOS 中的 JT 日历

iphone - 将整数拆分为单独的数字

ios - 如何下载 CoreCrypto.framework?

objective-c - 动态列出类的IBOutlets

ios - 在第一个关闭后显示第二个模态视图 Controller