私はいくつかの Objective-C でいくつかの問題を抱えており、いくつかの指針をいただければ幸いです。
だから私は次の単純なインターフェースを持つクラスMapFileGroup
を持っています(他のメンバー変数がありますが、それらは重要ではありません):
@interface MapFileGroup : NSObject {
NSMutableArray *mapArray;
}
@property (nonatomic, retain) NSMutableArray *mapArray;
mapArray
@synthesize
.m ファイルに含まれています。
init メソッドがあります。
-(MapFileGroup*) init
{
self = [super init];
if (self)
{
mapArray = [NSMutableArray arrayWithCapacity: 10];
}
return self;
}
また、配列にカスタム オブジェクトを追加するメソッドもあります。
-(BOOL) addMapFile:(MapFile*) mapfile
{
if (mapfile == nil) return NO;
mapArray addObject:mapfile];
return YES;
}
このクラスを使用したいときに問題が発生します-明らかに、私の側のメモリ管理の誤解が原因です。
私のView Controllerでは、次のように宣言します。
(@interface で):
MapFileGroup *fullGroupOfMaps;
@プロパティ付き@property (nonatomic, retain) MapFileGroup *fullGroupOfMaps;
次に、.m ファイルにloadMapData
は、次のことを行う関数が呼び出されます。
MapFileGroup *mapContainer = [[MapFileGroup alloc] init];
// create a predicate that we can use to filter an array
// .png で終わるすべての文字列 (大文字と小文字を区別しない)
mapNames = [unfilteredArray filteredArrayUsingPredicate:caseInsensitivePNGFiles];
[mapNames retain];
NSEnumerator * enumerator = [mapNames objectEnumerator];
NSString * currentFileName;
NSString *nameOfMap;
MapFile *mapfile;
while(currentFileName = [enumerator nextObject]) {
nameOfMap = [currentFileName substringToIndex:[currentFileName length]-4]; //strip the extension
mapfile = [[MapFile alloc] initWithName:nameOfMap];
[mapfile retain];
// add to array
[fullGroupOfMaps addMapFile:mapfile];
}
これは問題なく動作しているようです (メモリ管理が適切に機能していないことはわかりますが、まだ Objective-C を学習中です)。ただし、後者(IBAction)
と相互作用する がありfullGroupOfMaps
ます。内のメソッドを呼び出しますが、fullGroupOfMaps
デバッグ中にその行からクラスにステップ インすると、すべてfullGroupOfMaps
の のオブジェクトが範囲外になり、クラッシュします。
長い質問と大量のコードをお詫びしますが、私の主な質問は次のとおりです。
インスタンス変数として NSMutableArray を持つクラスをどのように処理すればよいですか? クラスに追加するオブジェクトを作成して、処理が完了する前にオブジェクトが解放されないようにする適切な方法は何ですか?
どうもありがとう