问题是重新分配已分配的对象

时间:2011-08-13 15:12:29

标签: objective-c release alloc

[searchDict release]发生崩溃。如果我切换两条最新线路的顺序,它仍会在最新线路上崩溃(现在[searchArray release])。我对Objective C很新,我想我没有得到正确的分配/释放...帮助? :)

NSMutableDictionary *searchDict = [[NSMutableDictionary alloc] init];
NSMutableArray *searchArray = [[NSMutableArray alloc] init];

for(int i = 0; i < 2; i++) { // Run two times ("Favorites" and "All")
    searchDict = [listOfItems objectAtIndex:i];
    searchArray = [searchDict objectForKey:@"Entries"];

    for (NSString *sTemp in searchArray) {
        NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
        if (titleResultsRange.length > 0)
            [listOfItemsDynamic addObject:sTemp];
    }
}

[searchArray release];
[searchDict release];

1 个答案:

答案 0 :(得分:5)

您可以分配空间并将其分配给变量:

NSMutableDictionary *searchDict = [[NSMutableDictionary alloc] init];
NSMutableArray *searchArray = [[NSMutableArray alloc] init];

但是你将非本地分配的数据分配给它们:

searchDict = [listOfItems objectAtIndex:i];
searchArray = [searchDict objectForKey:@"Entries"];

所以基本上,你不需要分配和发布。而是做这样的事情:

NSMutableDictionary *searchDict; // Just declartion, no allocation / init
NSMutableArray *searchArray;     // Just declartion, no allocation / init

for(int i = 0; i < 2; i++) { // Run two times ("Favorites" and "All")
    searchDict = [listOfItems objectAtIndex:i];
    searchArray = [searchDict objectForKey:@"Entries"];

    for (NSString *sTemp in searchArray) {
        NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
        if (titleResultsRange.length > 0)
            [listOfItemsDynamic addObject:sTemp];
    }
}

// No release needed here

如果您熟悉C,则类似于:

char *pChar;
pChar = malloc(15); // allocate memory and assign to pChar
pChar = "Hello";    // assign new address to pChar
free(pChar); // Error here ;)