以下是简单的代码:
// let's assume that I have to allocate this variable with alloc/init
NSString *someString = [[NSString alloc] initWithFormat:"%@", @"someString"];
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
[someClass someFunction: someString];
}];
[queue addOperation:op]
[someString release];
自从someString发布以来运行nsblockoperation时,此代码将崩溃。 防止这种情况的最佳做法是什么?
谢谢。
编辑:ARC不是一个选择,因为它不是我的决定。有什么方法可以在MRC中解决这个问题吗?
EDIT2:以下代码怎么样?它会起作用吗?
// let's assume that I have to allocate this variable with alloc/init
NSString *someString = [[NSString alloc] initWithFormat:"%@", @"someString"];
[someString retain]
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
[someClass someFunction: someString];
[someString release]
}];
[queue addOperation:op]
[someString release];
答案 0 :(得分:0)
// let's say the variable is allocated with alloc/init
NSString *someString = [[[NSString alloc] initWithFormat:"%@", @"someString"] autorelease];
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
[someClass someFunction: someString];
}];
[queue addOperation:op];
周围有数十万个应用程序需要维护,不要使用ARC。将字符串包裹在自动释放中。我认为这应该有用,但我没有测试。
答案 1 :(得分:-1)
您确实应该使用自动引用计数,并将代码简化为
// let's say the variable is allocated with alloc/init
NSString *someString = @"someString";
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
[someClass someFunction: someString];
}];
[queue addOperation:op]
如果您真的必须使用手动参考计数,您可以这样做:
// let's assume that I have to allocate this variable with alloc/init
NSString *someString = [[NSString alloc] initWithFormat:"%@", @"someString"];
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
[someClass someFunction: someString];
[someString release]
}];
[queue addOperation:op]
我知道它只是示例代码,但如果不是,你也可以这样做......;)
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
[someClass someFunction:@"someString"];
}];
[queue addOperation:op]