访问返回对象的属性会导致EXC_BAD_ACCESS

时间:2011-09-27 23:27:13

标签: iphone objective-c cocoa-touch memory-management

我定义了一个类,其中前两个属性可以无问题地访问。只有UIColor*才有问题。我认为某些东西没有被正确分配,初始化,保留或释放,并且一直在改变各种事情而没有成功。任何帮助都会很棒。

// PieceScore.h

@interface PieceScore : NSObject {
    int     pieceCount;
    BOOL    greatMatch;
    UIColor *colorMatched;
}

@property (nonatomic) int pieceCount;
@property (nonatomic) BOOL greatMatch;
@property (nonatomic, retain) UIColor *colorMatched;

-(id) initWithPieceCount:(int)pC withGreatMatch:(BOOL)gM withColorMatched:(UIColor*)cM;

@end


// PieceScore.m

@implementation PieceScore

@synthesize pieceCount, greatMatch, colorMatched;

-(id) init {
    return [self initWithPieceCount:0 withGreatMatch:NO withColorMatched:[UIColor clearColor]];
}

-(id) initWithPieceCount:(int)pC withGreatMatch:(BOOL)gM withColorMatched:(UIColor*)cM {
    self = [super init];
    if (self) {
        pieceCount = pC;
        greatMatch = gM;
        colorMatched = cM;
    }
    return self;
}

@end

它被初始化并由另一个类返回如下:

PieceScore* pieceScore = [[[PieceScore alloc] initWithPieceCount:piecesRemoved withGreatMatch:greatMatch withColorMatched:pieceColor] autorelease];
return pieceScore;

注意:(pieceColorUIColor*

然后,UIColor*用于另一个类的方法:

- (void) labelRender:(UILabel*)label withColor:(UIColor *)color {
    // ...

    label.textColor = color; // Thread 1: Program received signal: "EXC_BAD_ACCESS".

    // ...
}

在调试视图中,我可以看到color实际上是作为UIColor*传递的,但在分配给标签的textColor属性时错误输出。

2 个答案:

答案 0 :(得分:0)

您正在将ivar设置为自动释放的变量。确保使用该属性以便正确保留它。

colorMatched = cM;更改为self.colorMatched = cM;

答案 1 :(得分:0)

initWithPieceCount中的ivars:piecesRemoved:withGreatMatch:withColorMatched需要确保它们保留可以作为自动释放提供的任何值。您不应该在init方法中使用属性,

See here for some discussion

对传递的对象进行保留。

即。 colormatched = [cM retain];