プレーヤー クラスで 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