释放已经释放的内存

时间:2014-04-10 22:01:25

标签: objective-c

下面的主要方法应该多次调用BNRItem randomItem,但XCode在此行停止

 NSString *randomName = [NSString stringWithFormat:@"%@ %@",
                                [randomAdjectiveList objectAtIndex: adjectiveIndex],
                                [randomNounList objectAtIndex: nounIndex]];

错误

Thread 1 : EXC_BAD_ACCESS (Code = 1, address = 0x18)

我在SO上查找了这个错误(例如,这里Thread 1 : EXC_BAD_ACCESS (Code = 1, address = 0x30000008) issue generated),但无法弄清楚为什么会出现此问题。那个答案说,

this type of problem occurs when you release the memory assigned to an object that has been already released.

但是,我不知道这是怎么回事。你能解释一下......

int main(int argc, const char * argv[])
{

    @autoreleasepool {
     NSMutableArray *items = [[NSMutableArray alloc] init];

        for (int i = 0; i < 10; i ++){
            BNRItem *p = [BNRItem randomItem];
            [items addObject:p];

        }
        for (int i = 0; i < [items count]; i++){
            NSLog(@" %@", [items objectAtIndex:i]);
        }


        items = nil;

    }
    return 0;
}

BNRItem.m

+(id)randomItem
{
    NSArray *randomAdjectiveList = [[NSArray alloc] initWithObjects:@"Dumb", @"Hairy", @"Boring", nil];
    NSLog(@" %@", randomAdjectiveList);
    NSArray *randomNounList = [[NSArray alloc] initWithObjects:@"Car", @"Bar", "toy", nil];


    NSInteger adjectiveIndex = arc4random() % [randomAdjectiveList count];
    NSInteger nounIndex = arc4random() % [randomNounList count];


    NSString *randomName = [NSString stringWithFormat:@"%@ %@",
                            [randomAdjectiveList objectAtIndex: adjectiveIndex],
                            [randomNounList objectAtIndex: nounIndex]];

    int randomValue = arc4random() % 100;

    NSString *randomSerialNumber = [NSString stringWithFormat:@"%c %c %c %c %c",
                                    'O' + arc4random() % 100,
                                    'A' + arc4random() % 100,
                                    '0' + arc4random() % 100,
                                    'A' + arc4random() % 50,
                                    'O' + arc4random() % 25];
    BNRItem *newItem = [[ self alloc] initWithItemName:randomName valueInDollars:randomValue serialNumber:randomSerialNumber];

    return newItem;


}

1 个答案:

答案 0 :(得分:5)

哈哈!我之前也遇到过这个错误。问题出在你的

    NSArray *randomNounList = [[NSArray alloc] initWithObjects:@"Car", @"Bar", "toy", nil];

&#34;玩具&#34;之前应该有一个@符号。您正在使用标准c字符串(不是对象)执行initWithObject