我認爲只有三分之一的變量必須在dealloc方法中釋放。是對的嗎?
// no. your dealloc should look like this:
- (void)dealloc {
// note: *not* using accessors in dealloc
[view release], view = nil;
[scopeBar release], scopeBar = nil;
[array release], array = nil;
[super dealloc];
}
// your assignment of `scopeBar` should look like this:
...
self.scopeBar = (UISegmentedControl *)subView;
...
// you want to retain the view, as advertised.
// consider avoiding an ivar if you can easily access it.
// your assignment of `view` should look like this:
...
self.view = theView;
...
// you want to retain the view, as advertised.
// consider avoiding an ivar if you can easily access it.
// your assignment of `array` should look like this in your initializer:
// note: *not* using accessors in initializer
...
// identical to `array = [[NSMutableArray alloc] init];`
array = [NSMutableArray new];
...
// and the assignment of `array` should look like this in other areas:
...
self.array = [NSMutableArray array];
...
// you're likely to be best suited to declare your array as
// follows (assuming you really need a mutable array):
...
NSMutableArray *array; // << the declaration of the ivar
...
...
// the declaration of the public accessors.
// note the array is copied, and passed/returned as NSArray
@property (nonatomic, copy) NSArray *array;
...
// finally, the implementation manual of the properties:
- (NSArray *)array {
// copy+autorelease is optional, but a good safety measure
return [[array copy] autorelease];
}
- (void)setArray:(NSArray *)arg {
NSMutableArray * cp = [arg mutableCopy];
// lock? notify?
NSMutableArray * prev = array;
array = cp;
[prev release], prev = nil;
// unlock? notify? update?
}
其他答案假設懸擺指針(例如,你仍然持有一個指針來查看,但認爲可能已經在你的背後改變)是允許的。
他們不應該被允許在真正的程序。他們是非常危險的,並且很難重現他們造成的錯誤。因此,您必須確保您擁有對您維護/保持的指針的引用。
你也應該在公共接口中使用訪問器爲了子類型的緣故 - 如果它們覆蓋它們。如果你不想允許/支持,只需考慮使用一個私有變量。
要麼釋放(並可選擇將伊娃設置爲零),要麼調用setter--永遠都不會! – 2011-03-17 14:19:22