开发者

NSString init or alloc error?

开发者 https://www.devze.com 2023-03-09 18:42 出处:网络
I have this interface: #import <Foundation/Foundation.h> @interface Cards : NSObject {NSString* effect;NSString* image;}

I have this interface:

 #import <Foundation/Foundation.h>
 @interface Cards : NSObject {  NSString* effect;   NSString* image;   }
-(NSString*) 开发者_运维知识库effect;
-(NSString*) image;
-(void) setEffect: (NSString*) effect2;
-(void) setImage: (NSString*) image2;

@end

And this implementation:

#import "Cards.h"
@implementation Cards
-(NSString*) effect
{
    return [effect autorelease];
}
-(NSString*) image
{
    return [image autorelease];
}
-(void) setEffect: (NSString*) effect2
{
  effect = [[NSString alloc]initWithString:effect2];
}
-(void) setImage: (NSString*) image2
{
  image = [[NSString alloc]initWithString:@""];
}
-(void) dealloc
{
    [effect release];
    [image release];
    [super dealloc];
}
@end

Now if I make a Cards object such as Cards* card and then I run the metod setEffect like so: [card setEffect:@""]; It compiles but gives me a runtime error. Anyone know why? Thanks in advance!


I think you intended [image autorelease] to be [[image retain] autorelease]. Otherwise you will be autoreleasing it on every access of the property. You are also leaking on you set* methods as you're not releasing the older values prior to assigning the new one.


In your getter methods, you are returning an autoreleased object which may have never been allocated to begin with. In other words, you are only allocating the objects in your setter. If you want your objects to be returned autoreleased, you have to allocate them first, and then return them autoreleased.

You may be better off to create properties for each ivar and have them retained and released by the class. You would still need to allocate them, if they have not been allocated, which you may want to override the getter to do. Something like this.

-(NSString *)effect {
    if (!effect) {
        effect = [[NSString alloc] init];
    }
return effect;

in your header you would have

NSString *effect;

and then the property

@property(nonatomic, retain) NSString *effect;

then in the implementation you would synthesize

@synthesize effect;

and release in your -(void)dealloc

[effect release];

This way after you make a Card class you can call things like

card.effect = @"Whatever goes in the effect property";

//assuming card is a Card object

Hope this helps.

0

精彩评论

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