开发者

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 {

    NSStrin开发者_开发百科g *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];
    }
.........
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜