开发者

alloc and release problems

I can't figure out why my app is crashing after a few times I'm doing:

potionsT is nonatomic, retain, readonly.

-(void)First:(NSString*)Potions {

    potionsT = [开发者_C百科[NSString alloc] initWithString:Potions];
}

-(void)After:(NSString*)Potions {
    [potionsT release];
    potionsT = [[NSString alloc] initWithString:Potions];

You see, I'm first calling First and after that I'm calling a few times After: and wopes, it crashes. with ECX_BAD_ACCESS.. I'm pretty noob with all that memory manage thing, I know that... Thanks!


The point of retained property is it handles retain and release when you set it.

- (void)first:(NSString*)potions
{
    self.potionsT = potions; // will automatically release old value and retain new
}

- (void)after:(NSString*)potions
{
    self.potionsT = potions; // same as above
}

Also note how i renamed your Potions to potions, First: to first:, and After: to after:. Objective-C naming convention is to start variables and methods with lowercase letter, and class names with capital.


Did you @synthesize the property in the @implementation for the class? If so, then you should use:

self.potionsT = Potions;

if you use

potionsT = ...

then you are accessing the ivar, not the property. To access the property and let it do the memory management for you, you must precede it with an instance reference, and that can also be self.

If you use the property, you should not release potionsT manually, since the property already does that for you.


If you've set up potionsT as a property, you should access it that way:

-(void)first:(NSString*)potions {
    self.potionsT = potions;
}

-(void)after:(NSString*)potions {
    self.potionsT = potions;
}

In both cases, I changed your code to use the accessor for potionsT (that's what the self.potionsT means). I'm also not creating a new string, but just retaining the provided one. Since NSStrings are immutable, the result is the same. For best results, though, change the potionT property from retain to copy. That way, if a mutable string gets passed in, it'll be copied instead of retained (and immutable strings will still just be retained).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜