problem with NSString, it's losing it's value after assigning it to a function parameter

余生长醉 提交于 2020-01-03 04:52:10

问题


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;
.........
}

回答1:


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

@interface PageViewController : UIViewController {

    NSString *mystring;
}

@property (nonatomic, retain) NSString *mystring;

Then in your implementation,

@synthesize mystring;

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

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

[self setMystring:@"something"];

or

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];

Lastly, in your function:

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



回答2:


It's not completely clear what you mean by 'losing its value', but I think the problem here is one of memory management- you need to do some reading of how Cocoa handles this, but in this case you'll need to do:

-(void) function_definition:(NSString *) param {
.............
    if (mystring != param) {
        [mystring release];
        mystring = [param retain];
    }
.........
}


来源:https://stackoverflow.com/questions/5398695/problem-with-nsstring-its-losing-its-value-after-assigning-it-to-a-function-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!