0

iOS の新機能であり、NSMutable 配列にオブジェクトを追加し、アプリ内の別のビューに配列を表示することに関して、1 つの問題で立ち往生しています。データは TableView の他のビューに正常に表示されますが、配列に別の項目を追加すると (以下のコードを使用)、配列に追加するのではなく、そこにあったものを置き換えるだけです。

- (void) postArray {
tableData = [[NSMutableArray alloc] initWithCapacity:10];
tableData = [[NSMutableArray alloc] initWithObjects: nil];
[tableData addObject:favShot]; }

-(NSString *) saveFilePath {

NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, TRUE);
return [[path objectAtIndex:0] stringByAppendingPathComponent:@"savefile.plist"]; }

- (void) viewWillDisappear:(BOOL)animated: (UIApplication *) application  {
NSArray *values = [[NSArray alloc] initWithObjects:tableData, nil];
[values writeToFile:[self saveFilePath] atomically: TRUE]; }

- (void)viewDidLoad  {

tableData = [[NSMutableArray alloc] initWithObjects: nil];

NSString *myPath = [self saveFilePath];

BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];

if (fileExists)
{

    NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath];
    tableData = [values mutable copy];
}

UIApplication *myApp = [UIApplication sharedApplication];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(applicationDidEnterBackground:)
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:myApp];

[super viewDidLoad];  }

ありがとうございました。

4

2 に答える 2

0

呼び出すたびpostArrayに のインスタンスを作成しNSMutableArray、それを破棄します (ARC を使用していない場合はリークします)。次に、 の別のインスタンスを作成していますNSMutableArray。次に、その 2 番目のインスタンスにオブジェクト (favShot) を追加します。

次に呼び出すpostArrayと、古い配列が破棄され、2 つの新しい配列が作成されます。

やりたいことはtableData、コントローラー インスタンスの作成時、またはビューの読み込み時にインスタンスを作成することです。tableData = ...次に、古いインスタンスを破棄するため、設定しないでください。オブジェクトを追加および削除するだけです。

編集

- (void) postArray {
[tableData addObject:favShot];
}

- (NSString *)saveFilePath {
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, TRUE);
return [[path objectAtIndex:0] stringByAppendingPathComponent:@"savefile.plist"];
}

- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];

[tableData writeToFile:[self saveFilePath] atomically: TRUE];
}

- (void)viewDidLoad  {
NSString *myPath = [self saveFilePath];

BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];

if (fileExists)
{
    tableData = [[NSMutableArray alloc] initWithContentsOfFile:myPath];
} else {
    tableData = [[NSMutableArray alloc] initWithObjects: nil];
}

UIApplication *myApp = [UIApplication sharedApplication];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(applicationDidEnterBackground:)
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:myApp];

[super viewDidLoad];
}
于 2013-04-27T13:24:45.323 に答える