Ios 如何正确释放没有控制柄的指定对象
Instruments指出这是内存泄漏,但我不确定如何正确释放它,或者何时应该释放它。 是否有更好的约定用于为仅在循环中需要的新对象指定属性?具体行是Ios 如何正确释放没有控制柄的指定对象,ios,objective-c,memory-management,retain,Ios,Objective C,Memory Management,Retain,Instruments指出这是内存泄漏,但我不确定如何正确释放它,或者何时应该释放它。 是否有更好的约定用于为仅在循环中需要的新对象指定属性?具体行是expense.addedDate=[NSDate new] - (void) addObjects:(NSString *)itemDescription withItemAmount:(NSString *)itemAmount { // Add a new expense to the persistent store. NSString *
expense.addedDate=[NSDate new]代码>
- (void) addObjects:(NSString *)itemDescription withItemAmount:(NSString *)itemAmount {
// Add a new expense to the persistent store.
NSString *expenseDescription = itemDescription;
NSString *expenseAmount = itemAmount;
if (!expenseDescription.length || !expenseAmount.length) {
UIAlertView *invalidEntry = [[[UIAlertView alloc] initWithTitle:@"Invalid Entry"
message:@"You must include a description and cost."
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil] autorelease];
[invalidEntry show];
} else {
Expense *expense = (Expense *)[NSEntityDescription insertNewObjectForEntityForName:@"Expense"
inManagedObjectContext:self.managedObjectContext];
expense.addedDate = [NSDate new];
expense.itemDescription = expenseDescription;
expense.cost = [NSNumber numberWithInt:[expenseAmount intValue]];
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Error %@", [error localizedDescription]);
UIAlertView *errorSave = [[[UIAlertView alloc] initWithTitle:@"Unable to Save!"
message:@"Money manager was not able to save this entry."
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil] autorelease];
[errorSave show];
} else {
NSLog(@"Saved Expense to Database.");
}
}
}
我想您不想使用new
选择器,因为它不是自动释放的。如果要查找默认、当前时间戳、自动删除的NSDate对象,应使用:
expense.addedDate = [NSDate date];
记录在案
[NSObject new]
相当于
[[NSObject alloc] init]
如果您声明“expense.addedDate”属性以使用retain(@property(retain)),则不应像指定日期那样指定日期,因为对象的retainCount为2,稍后释放时将导致memleak
相反,使用自动释放对象或在指定后释放对象就足够了
e、 g
或
还是第三条路
NSDate* dt = [[NSDate new] autorelease];
自动释放(so#1或#3)是首选。
NSDate* dt = [NSDate new];
expense.addedDate = dt;
[dt release];
NSDate* dt = [[NSDate new] autorelease];