为什么在 viewDidLoad 中声明的数组在另一种方法中使用时会收到未使用的变量警告



我收到一个未使用的变量警告,警告我在viewDidLoad中声明的trucksArray数组。我不明白为什么,因为我在viewController.m中的另一种方法中使用它.

我对目标c非常陌生,所以如果这是一个非常简单的问题,我

提前道歉。

以下是方法:

- (void)viewDidLoad
{
    [super viewDidLoad];
    TruckLocation *a1 = [[TruckLocation alloc] initWithName:@"test truck 1" address:@"41 Truck Avenue, Provo, Utah" coordinate:CLLocationCoordinate2DMake(40.300828, 111.663802)];
    TruckLocation *a2 = [[TruckLocation alloc] initWithName:@"test truck 2" address:@"6 Truck street, Provo, Utah" coordinate:CLLocationCoordinate2DMake(40.300826, 111.663801)];
    NSMutableArray* trucksArray =[NSMutableArray arrayWithObjects: a1, a2, nil];
}

以及我使用数组的方法:

- (void)plotTruckPositions:(NSData *)responseData {
    for (id<MKAnnotation> annotation in _mapView.annotations) {
        [_mapView removeAnnotation:annotation];
    }
    NSDictionary *root = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
    NSMutableArray *trucksArray = [root objectForKey:@"trucksArray"];
    for (NSArray *row in trucksArray) {
        NSNumber * latitude = [row objectAtIndex:1];
        NSNumber * longitude = [row objectAtIndex:2];
        NSString * truckDescription = [row objectAtIndex:2];
        NSString * address = [row objectAtIndex:3];
        CLLocationCoordinate2D coordinate;
        coordinate.latitude = latitude.doubleValue;
        coordinate.longitude = longitude.doubleValue;
        TruckLocation *annotation = [[TruckLocation alloc] initWithName:truckDescription address:address coordinate:coordinate] ;
        [_mapView addAnnotation:annotation];
    }
}

在 viewDidLoad 中,您正在创建一个 NSMutableArray 的实例,该实例在 viewDidLoad 方法结束后被释放。在第二种方法中,您将创建一个完全不同的 NSMutableArray。如果您打算在某处创建该 NSMutableArray 并在其他地方使用它,则应创建一个实例变量或属性来保留对该 NSMutableArray 的引用。

@property (nonatomic) NSMutableArray *trucksArray;

您正在使用两个完全不同的数组,它们恰好都被称为 trucksArray

在您的 viewDidLoad 方法中,您正在创建的数组不会存储在任何位置,因此它会超出范围,并在方法返回后释放。您的意思是将其分配给实例变量吗?

如果您在标头中将变量声明为全局变量(带大括号),则只需要分配它们,而无需重新声明它们只是分配它们(等号),即省略前面的"TruckLocation *"。