NSString的问题,将其赋值给函数参数后会丢失它的值 [英] problem with NSString, it's losing it's value after assigning it to a function parameter

查看:93
本文介绍了NSString的问题,将其赋值给函数参数后会丢失它的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Objective-C真的很奇怪,我无法理解... 如果我尝试重新分配它,我有一个NSstring会失去它的价值... 这是我的使用方法. 谁能告诉我我在做什么错?这是在分配新值时发生的.

Objective-C is really wierd, i can't get the hang of it... I have a NSstring that is losing it's value if I try to reassign it... Here's how I use it.. Can anyone tell me what am I doing wrong? it's happening at the assigning of the new value..

@interface PageViewController : UIViewController {

    NSString *mystring;
}


- (void)viewDidLoad {

    mystring=[ [NSString alloc] initWithString:@""];
}


-(void) function_definition:(NSString *) param {
.............
    mystring=param;
.........
}

推荐答案

通常,您希望将其指定为属性:

Most commonly, you would want to designate this as a property:

@interface PageViewController : UIViewController {

    NSString *mystring;
}

@property (nonatomic, retain) NSString *mystring;

然后在您的实现中,

@synthesize mystring;

- (void)dealloc {
    [mystring release];
    [super dealloc];
}

最后,在实现的任何地方,使用以下任一方法设置mystring的值:

And finally, anywhere in your implementation, set the value of mystring by using either:

[self setMystring:@"something"];

self.mystring = @"somethingelse";

如果要分配新字符串,请确保将其释放.使用该属性会自动保留它.

If you're allocating a new string, be sure to release it. It's retained automatically using the property.

self.mystring = [[[NSString alloc] initWithString:@"hello"] autorelease];

最后,在您的函数中:

-(void) function_definition:(NSString *) param {
.............
    self.mystring = param;
.........
}

这篇关于NSString的问题,将其赋值给函数参数后会丢失它的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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