简体   繁体   中英

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

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;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM