我有一个生成Deck对象的方法(带有NSMutableArray属性的NSObject子类),它用Card对象填充数组(UIView子类带有一些整数和一个NSString属性)。当我要求甲板时,我会检查是否已存在(我认为),如果存在,请在获得新的之前将其释放。
我的viewcontroller中的代码......
#import "FlashTestViewController.h"
@implementation FlashTestViewController
- (IBAction)generateDeck {
if (aDeck != nil) {
[aDeck release];
}
aDeck = [[Deck alloc] initDeckWithOperator:@"+"];
}
- (IBAction)generateCard {
if (aCard != nil) {
[aCard fadeAway];
}
aCard = [aDeck newCardFromDeck];
[self.view addSubview:aCard];
}
- (void)fadeAway {
[aCard removeFromSuperview];
[aCard release];
}
@end
甲板课程如下......
#import <Foundation/Foundation.h>
#import "Card.h"
@class Deck;
@interface Deck : NSObject {
NSMutableArray* cards;
}
@property(nonatomic, retain) NSMutableArray* cards;
- (id)initDeckWithOperator: (NSString*)mathOper;
- (id)newCardFromDeck;
@end
- (id)initDeckWithOperator: (NSString*)mathOper {
if (cards != nil) {
[cards release];
}
cards = [[NSMutableArray alloc] init];
for (int i=0; i<11; i++) {
for (int j=0; j<11; j++) {
int xPos = (random() % 220) + 10;
int yPos = (random() % 360) + 10;
Card* aCard = [[Card alloc] initWithFrame:CGRectMake(xPos, yPos, 60, 80)];
aCard.upperOperand = i;
aCard.lowerOperand = j;
aCard.theOperator = mathOper;
aCard.theResult = i + j;
UITextView* upperTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, 50, 20)];
NSString* upperOper = [[NSString alloc] initWithFormat:@" %d", i];
upperTextView.text = upperOper;
[aCard addSubview:upperTextView];
[upperTextView release];
[upperOper release];
UITextView* middleTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, 30, 50, 20)];
NSString* middleOper = [[NSString alloc] initWithFormat:@"%@ %d", mathOper, j];
middleTextView.text = middleOper;
[aCard addSubview:middleTextView];
[middleTextView release];
[middleOper release];
UITextView* lowerTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, 55, 50, 20)];
NSString* lowerOper = [[NSString alloc] initWithFormat:@" %d", j+i];
lowerTextView.text = lowerOper;
[aCard addSubview:lowerTextView];
[lowerTextView release];
[lowerOper release];
[cards addObject: aCard];
[aCard release];
}
}
return self;
}
- (id)newCardFromDeck {
int index = random() % [cards count];
Card* selectedCard = [[cards objectAtIndex:index] retain];
[cards removeObjectAtIndex:index];
return selectedCard;
}
@end
当我从newCardFromDeck方法中请求一张新卡时,我做了同样的事情。有什么建议吗?
谢谢!
答案 0 :(得分:2)
看看这行代码:
cards = [[NSMutableArray alloc] init];
您是否在cards
方法中发布了dealloc
?看起来这可能可能是内存泄漏。
答案 1 :(得分:2)
将此代码添加到Deck.m文件中:
- (void)dealloc
{
[cards release];
[super dealloc];
}
答案 2 :(得分:0)
答案 3 :(得分:0)
在newCardFromDeck中:
Card* selectedCard = [[cards objectAtIndex:index] retain];
看起来你保留了卡并将其归还给某个地方。这个回报值最终会在哪里?如果它在另一个带有'retain'属性的变量中结束,它可以第二次保留(在赋值给变量时)。