我在设置传递指向nil的指针时遇到问题。当我通过GDB运行以下代码时,我看到传递的变量“string”在被调用函数中被本地设置为nil,但是在调用它的范围内,它仍然指向原始内存地址。我认为这个问题的解决方案将涉及一个引用和解引用运算符的组合,我只是在基本面上不够好,无法计算出这个:)
#import "AppDelegate.h"
@interface AppDelegate()
+(void)releaseAndNullify:(id)input;
@end
@implementation AppDelegate
@synthesize window;
-(void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSString *string = [NSString string];
[AppDelegate releaseAndNullify:string];
}
+(void)releaseAndNullify:(id)input
{
if (input)
{
[input release];
input = nil;
}
}
-(void)dealloc
{
[window release];
[super dealloc];
}
@end
答案 0 :(得分:1)
Objective-C参数按值传递,而不是参考。
答案 1 :(得分:1)
以下是我从另一篇文章中找到的解决方法:
#import "AppDelegate.h"
@interface AppDelegate()
+(void)releaseAndNullify:(NSString **)input;
@end
@implementation AppDelegate
@synthesize window;
-(void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
NSString *string = [NSString string];
[AppDelegate releaseAndNullify:&string];
}
+(void)releaseAndNullify:(NSString **)input
{
if (!*input) return;
[*input release];
*input = nil;
}
-(void)dealloc
{
[window release];
[super dealloc];
}
@end