Instruments 指出这是内存泄漏,但我不确定如何正确释放它,或者何时应该释放它。是否有更好的约定为仅在循环内需要的新对象分配属性?具体线路是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.");
}
}
}