我在播放器类中分配 NSMutableArray 时遇到问题,当我在 (id)init 方法中尝试这种方式时,编译时没有警告: playerInventory = [[NSMutableArray alloc] init]; 但是当我运行程序时,它给了我一个错误(EXC_BAD_ACCESS)。我一遍又一遍地检查,但没有发现任何帮助。我是objective c的新手,我对这种语言的内存管理知识不多。但似乎我尽了最大的努力找不到答案。
.h 文件
@interface Player : NSObject
{
int playerLevel;
int playerExp;
NSMutableArray *playerInventory;
NSString *playerName;
BOOL isLastPlayerExist;
NSData *xmlData;
GDataXMLDocument *_xmlDoc;
}
@property (assign,readwrite) int playerLevel;
@property (retain,readonly) NSString *playerName;
@property (assign,readonly) BOOL isLastPlayerExist;
@property (retain,readwrite) NSMutableArray *playerInventory;
+(Player *)currentPlayer;
-(void)loadXMLFile;
-(void)loadRecentPlayer;
-(void)loadPlayerStats;
-(void)loadPlayerInventory;
-(void)releaseXMLFile;
@end
.m 文件,删除了不相关的实现。
@implementation Player
static Player *sharedInstance = nil;
@synthesize playerLevel;
@synthesize playerName;
@synthesize isLastPlayerExist;
@synthesize playerInventory;
-(id) init{
self = [super init];
if (self != nil){
playerInventory = [[NSMutableArray alloc] init];
[self loadXMLFile];
[self loadRecentPlayer];
[self loadPlayerStats];
}
return self;
}
-(void) loadXMLFile{
NSString *filePath = [self dataFilePath: NO];
xmlData = [[NSMutableData alloc] initWithContentsOfFile:filePath];
NSError *error;
_xmlDoc = [[GDataXMLDocument alloc] initWithData:xmlData
options:0 error:&error];
}
-(void) loadRecentPlayer{
NSArray *playerInfo = [_xmlDoc.rootElement elementsForName:@"Player"];
GDataXMLElement *currentName = (GDataXMLElement *)[playerInfo objectAtIndex:0];
playerName = currentName.stringValue;
NSLog(@"%@",playerName);
}
-(void) loadPlayerStats{
NSString *xPath;
NSArray *playerInfo;
xPath = [NSString stringWithFormat:@"//Users/Player[Name = \"%@\"]/Level",playerName];
playerInfo = [_xmlDoc.rootElement nodesForXPath:xPath error: nil];
GDataXMLElement *level = (GDataXMLElement *)[playerInfo objectAtIndex:0];
playerLevel = level.stringValue.intValue;
xPath = [NSString stringWithFormat:@"//Users/Player[Name = \"%@\"]/Experience",playerName];
playerInfo = [_xmlDoc.rootElement nodesForXPath:xPath error: nil];
GDataXMLElement *exp = (GDataXMLElement *)[playerInfo objectAtIndex:0];
playerExp = exp.stringValue.intValue;
xPath = [NSString stringWithFormat:@"//Users/Player[Name = \"%@\"]/Inventory/CardID",playerName];
playerInfo = [_xmlDoc.rootElement nodesForXPath:xPath error: nil];
for(id obj in playerInfo){
GDataXMLElement *card = (GDataXMLElement *)obj;
[playerInventory addObject: card.stringValue.intValue];
NSLog(@"%d",card.stringValue.intValue);
}
NSLog(@"%@",playerInventory);
}
+(Player *)currentPlayer{
if (sharedInstance == nil){
sharedInstance = [[self alloc] init];
}
return sharedInstance;
}
- (NSString *)dataFilePath:(BOOL)forSave {
return [[NSBundle mainBundle] pathForResource:@"userData" ofType:@"xml"];
}
@end