Should IBOutlets be strong or weak under ARC?

后端 未结 11 2135
自闭症患者
自闭症患者 2020-11-22 01:52

I am developing exclusively for iOS 5 using ARC. Should IBOutlets to UIViews (and subclasses) be strong or weak?

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 02:40

    I don't see any problem with that. Pre-ARC, I've always made my IBOutlets assign, as they're already retained by their superviews. If you make them weak, you shouldn't have to nil them out in viewDidUnload, as you point out.

    One caveat: You can support iOS 4.x in an ARC project, but if you do, you can't use weak, so you'd have to make them assign, in which case you'd still want to nil the reference in viewDidUnload to avoid a dangling pointer. Here's an example of a dangling pointer bug I've experienced:

    A UIViewController has a UITextField for zip code. It uses CLLocationManager to reverse geocode the user's location and set the zip code. Here's the delegate callback:

    -(void)locationManager:(CLLocationManager *)manager
       didUpdateToLocation:(CLLocation *)newLocation
              fromLocation:(CLLocation *)oldLocation {
        Class geocoderClass = NSClassFromString(@"CLGeocoder");
        if (geocoderClass && IsEmpty(self.zip.text)) {
            id geocoder = [[geocoderClass alloc] init];
            [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
                if (self.zip && IsEmpty(self.zip.text)) {
                    self.zip.text = [[placemarks objectAtIndex:0] postalCode];
                }
            }];    
        }
        [self.locationManager stopUpdatingLocation];
    }
    

    I found that if I dismissed this view at the right time and didn't nil self.zip in viewDidUnload, the delegate callback could throw a bad access exception on self.zip.text.

提交回复
热议问题