Objective C重新分配/内存管理崩溃

时间:2011-03-12 01:21:17

标签: objective-c memory-management

作为一名相对的Objective-C初学者,我显然还没有掌握某些内存管理规则。我无法弄清楚如何使这不崩溃:

@interface MyClass { NSArray *playerArray4th; }

- (void) viewDidLoad { playerArray4th = [self getAudioPlayersForSoundFile:@"rimshot" ofType:@"aif"]; }

- (NSArray*) getAudioPlayersForSoundFile:(NSString*)soundFileName ofType:(NSString*)soundFileType {

    //code instantiating objects....

    NSArray *toRet = [[NSArray alloc] initWithObjects:toRetTickPlayer,toRetTickPlayerCopy,toRetTickPlayerCopy2,toRetTickPlayerCopy3, nil];
    return toRet;
}

然后,在另一个函数中:

NSArray *currentArray = playerArray4th;
[currentArray release];
currentArray = nil;
currentArray = [self getAudioPlayersForSoundFile:fileName ofType:ofType];

尝试再次访问阵列时崩溃了:

- (void) playSound:(NSString*)soundType {

    AVAudioPlayer *currentPlayer;

    if ([soundType isEqualToString:@"4th"]) {
        if (playerArray4thCounter >= [playerArray4th count]) playerArray4thCounter = 0;
        NSLog(@"Playing from array: %@",playerArray4th);
        currentPlayer = [playerArray4th objectAtIndex:playerArray4thCounter];
        playerArray4thCounter++;
    }
}

1 个答案:

答案 0 :(得分:0)

尝试了解properties以及有关使用getter和setter的信息。除非你确切知道发生了什么,否则不要走捷径。

因此,在头文件中定义playerArray4th属性:

@property (nonatomic,retain) NSArray *playerArray4th;

然后在你的.m文件中创建getter / setter:

@synthesize playerArray4th;

然后,总是使用self.playerArray4th来分配和获取变量。先前的对象将在需要时释放。

所以这不会泄漏:

self.playerArray4th = [NSArray arrayWithObjects:@"text",@"text",nil];
self.playerArray4th = [NSArray arrayWithObjects:@"new array",@"text",nil];

因为第二个赋值会释放第一个数组。

此外,请阅读有关使用autorelease的信息。简而言之,如果您alloccopynew,则应releaseautorelease。这里有很多关于此的内容,我现在不再重复了。

不要忘记将self.playerArray4th = nil;放入dealloc方法。