1

我想释放经销商中存在的汽车对象。我想知道什么是正确的做法。NSMutableArray Inventory 存储特定经销商的汽车。所以,现在我想向用户展示一个删除功能,因此,用户可以使用 Vin Number 选择汽车并将其删除。但是,如果我试图找到汽车并释放不起作用的参考。我需要从数组中删除对象然后释放引用吗?我对目标 c 和初始学习阶段相当陌生。谢谢你。

#import "Dealer.h"
#import "Address.h"
#import "PhoneNumber.h"

@implementation Dealer

static NSInteger dealerIdAllocater = 0;

-(id) init{
    self = [super init];
    self.dealerId = ++dealerIdAllocater;
    self.addressList = [[NSMutableArray alloc] init];
    self.inventory = [[NSMutableArray alloc] init];
    return self;
}

@synthesize dealerId, name, addressList, inventory;

-(void)addCarInInventory:(Car*)car{
    [self.inventory addObject: car];
}

-(void)displayAddresses{
    for(Address *address in self.addressList){
        NSLog(@"Street Address: %@", address.streetAddress);
        NSLog(@"City: %@", address.city);
        NSLog(@"State: %@", address.state);
        NSLog(@"Country: %@", address.country);
        for(int i=0; i<[address.phoneNumber count]; i++){
            PhoneNumber *phoneNumber = [address.phoneNumber objectAtIndex:i];
            NSLog(@"Phone Number %i, %@", i, phoneNumber.phoneNumber);
        }
        NSLog(@"--------------");
    }
}

-(void)displayInventory{
    for(Car *car in self.inventory){
        [car displayInformation];
    }
    NSLog(@"--------------");
}

-(Car *)findCarById:(NSString *)vinNumber{
    for(Car *car in self.inventory){
        if ([vinNumber isEqualToString:car.vinNumber]) {
            return car;
        }
    }
    return nil;
}

@end
4

1 回答 1

1

我需要从数组中删除对象然后释放引用吗?

是的,像NSMutableArrays 这样的容器在添加对象时会将对象的保留计数增加 1。这是为了确保容器始终持有对对象的有效引用。当您从容器中移除一个对象时,保留计数将减 1。

于 2013-02-15T10:01:39.650 回答