如何正确释放没有句柄的已分配对象

时间:2010-09-09 00:57:18

标签: ios objective-c memory-management retain

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

2 个答案:

答案 0 :(得分:1)

我认为你不想使用new选择器,因为它不是自动发布的。如果您正在寻找默认的当前时间戳,自动释放的NSDate对象,您应该使用:

expense.addedDate = [NSDate date];

记录,

[NSObject new]

相当于

[[NSObject alloc] init]

Apple's docs on the new method

答案 1 :(得分:1)

如果声明“expense.addedDate”的属性使用retain(@property(retain)),则不应该像操作那样分配日期,因为该对象的retainCount为2,稍后当它被释放时会导致一个memleak。

相反,它足以使用自动释放的对象或在分配之后释放对象。

e.g。

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

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

或第三种方式

NSDate* dt = [[NSDate new] autorelease];