问题重新分配分配的对象
Posted
技术标签:
【中文标题】问题重新分配分配的对象【英文标题】:Problem realeasing allocated objects 【发布时间】:2011-08-13 15:12:29 【问题描述】:崩溃发生在 [searchDict 版本]。如果我切换两个最新行的顺序,它仍然会在最新行(现在 [searchArray 版本])上崩溃。我对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】:您分配空间并将其分配给变量:
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 ;)
【讨论】:
以上是关于问题重新分配分配的对象的主要内容,如果未能解决你的问题,请参考以下文章
我应该在重新分配之前调用分配给保留属性的自动释放对象的释放吗?