Objective-C 中的排序和释放 NSArray
我正在尝试对一系列国家/地区进行排序。这种方法可行,但我不知道释放 tmpArray 的方法。我如何释放它?有更好的方法吗?
// PUT COUNTRIES IN ARRAY
NSString *myFile = [[NSBundle mainBundle] pathForResource:@"Countries" ofType:@"plist"];
NSArray *tmpArray = [[NSArray alloc] initWithContentsOfFile:myFile];
tmpArray = [tmpArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
arrayCountries = [[NSArray alloc] initWithArray:tmpArray] ;
// [tmpArray release];
I am trying to sort an array of countries. This way works, but I can't figure out the way to release tmpArray. How do I release it and is there a better way of doing this?
// PUT COUNTRIES IN ARRAY
NSString *myFile = [[NSBundle mainBundle] pathForResource:@"Countries" ofType:@"plist"];
NSArray *tmpArray = [[NSArray alloc] initWithContentsOfFile:myFile];
tmpArray = [tmpArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
arrayCountries = [[NSArray alloc] initWithArray:tmpArray] ;
// [tmpArray release];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要么
-autorelease
你分配/初始化的变量(因为当你用排序数组替换它时你会丢失对它的引用),或者使用另一个变量,如“sortedTmpArray'。
您当前正在做的是“创建此对象并将其分配给
tmpArray
”,然后“通过过滤此对象创建另一个数组并将其分配给tmpArray
”。那时,您不再拥有指向您创建的第一个数组的指针,因此无法释放它 - 它已泄漏。解决方案是在创建它时将其放入自动释放池中,或者仅使用两个单独的指针。或者,您可以第一次创建一个可变数组,然后使用
-sortUsingDescriptors:
对其进行就地排序,而不是创建两个单独的数组。Either
-autorelease
the one you alloc/init'd (because you're losing your reference to it when you replace it with the sorted array) or use another variable like 'sortedTmpArray
'.What you're currently doing is "create this object and assign it to
tmpArray
", then "create another array by filtering this one and assign it totmpArray
". At that point, you no longer have a pointer to the first array you created so there's no way to release it - it's leaked.The solution is to place it in the autorelease pool when you create it or just use two separate pointers. Alternatively, you can create a mutable array the first time and use
-sortUsingDescriptors:
to sort it in place instead of creating two separate arrays.