释放参数 [英] Releasing a parameter

查看:53
本文介绍了释放参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有班级在其他线程上做某事.并有自己的代表.

let's say if you have class doing something on some other thread. And has delegate of its own.

@protocol XRequestDelegate;

@interface XRequest : NSObject {
    id<XRequestDelegate> delegate;
}
@property (nonatomic, retain) id<XRequestDelegate> delegate;

- (void) doSomething;
@end


@protocol XRequestDelegate <NSObject>

- (void)request:(XRequest *)request didFinish:(id)object;
- (void)request:(XRequest *)request didFailWithError:(NSError*)error;

@end

doSomething 最终调用 request:didFinish:request:didFailWithError:

doSomething eventually calls either request:didFinish: or request:didFailWithError:

让我们在我们的对象中使用这个类;

and lets use this class in our object;

- (void)doRequest
{
    XRequest *request = [[XRequest alloc] init];
    [request setDelegate:self];
    [request doSomething];
}

- (void)request:(XRequest *)request didFinish:(id)object
{
    // Use object whatever you want
    [request release];
}

- (void)request:(XRequest *)request didFailWithError:(NSError *)error
{
    //Log Error
    [request release];
}

我们在方法中分配并最终释放了一个 XRequest 实例.

we have an instance of XRequest allocated and eventually released in methods.

我们能说这是一种错误的内存管理方式吗?我们是否应该扩大 XRequest 对象的范围?

Can we say this is a wrong way of memory management. Should we expand the scope of XRequest object?

推荐答案

Apple 的 内存管理的基本规则指出:

Apple's fundamental rule of memory management states:

您只能释放或自动释放您拥有的对象.

You only release or autorelease objects you own.

我认为在这种情况下,您不会违反该规则,因为您的委托是分配请求的对象.但是,您确实提到了多个线程,最佳实践是每个线程有一个对象(不要在一个线程上分配请求并在另一个线程上释放它).

I think in this case, you would not be breaking that rule, since your delegate is the object that allocated the request. You do mention multiple threads, however, and the best practice there is to have one object per thread (don't allocate the request on one thread and release it on another).

这篇关于释放参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆