【发布时间】:2011-03-17 12:51:56
【问题描述】:
我正在使用自定义类在表格视图上显示一些信息。 问题是只要我滚动tableview内存就会泄漏...
我想我的课堂出了点问题。
请看:
@interface Person : NSObject {
NSString *name;
NSString *surname;
NSString *address;
NSString *email;
}
@property (nonatomic, copy) NSString *name, *surname, *address, *email;
@implementation Person
@synthesize name, surname, address, email;
-(id)init {
[super init];
name = [[NSString alloc] init];
surname = [[NSString alloc] init];
address = [[NSString alloc] init];
email = [[NSString alloc] init];
return self;
}
- (void)dealloc
{
[name release];
[surname release];
[address release];
[email release];
[super dealloc];
}
#import "Person.h"
@interface Group : NSObject {
NSString *groupTitle;
NSMutableArray *persons;
}
@property (readwrite, copy) NSString *groupTitle;
- (void)addPerson:(Person *)person;
- (void)removeAll;
- (NSArray *)getPersons;
- (int)PersonsCount;
@end
@implementation Group
@synthesize groupTitle;
-(id)init {
[super init];
persons = [[NSMutableArray alloc] init];
return self;
}
-(void)addPerson:(Person *)person {
[persons addObject:person];
}
-(void)removeAll {
[persons removeAllObjects];
}
-(NSArray *) getPersons {
return [persons copy];
[persons release];
}
-(int)personsCount {
return [persons count];
}
-(void)dealloc {
[groupTitle release], groupTitle = nil;
[persons release], persons = nil;
[super dealloc];
}
@end
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
…….
Group *groupForRow = [[Group alloc] init];
Person *personForRow = [[Person alloc] init];
personForRow = [[groupForRow getPersons] objectAtIndex:indexPath.row];
_personName = personForRow.name;
_personSurname = personForRow.surname;
_personAddress = personForRow.address;
_personEmail = personForRow.email;
[groupForRow release], groupForRow = nil;
[personForRow release], personForRow = nil;
…..
return cell
【问题讨论】:
-
NSString 是不可变的。不要到处使用副本,并使用
retain而不是copy定义您的属性。 -
拥有
NSString属性作为副本很好,但alloc没有用(您只是分配空字符串)。
标签: iphone uitableview memory-management