0

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.");
    }
}
}
4

2 回答 2

1

如果您声明“expense.addedDate”的属性以使用保留 (@property(retain)),则不应像您那样分配日期,因为该对象的 retainCount 为 2,稍后当它被释放时会导致内存泄漏。

相反,使用自动释放对象或在分配后释放对象就足够了。

例如

expense.addedDate = [NSDate date];  // will return an autoreleased object

或者

NSDate* dt = [NSDate new];
expense.addedDate = dt;
[dt release];

或第三种方式

NSDate* dt = [[NSDate new] autorelease];
于 2010-09-09T01:28:37.877 回答
1

I think you don't want to use the new selector, as it is not auto-released. If you're looking for a default, current timestamp, autoreleased NSDate object, you should use:

expense.addedDate = [NSDate date];

For the record,

[NSObject new]

is equivalent to

[[NSObject alloc] init]

Apple's docs on the new method

于 2010-09-09T01:02:40.190 回答