目标C:如何在方法具有返回类型的方法中或在具有任何返回类型的重写方法中设置NSAutoreleasePool



如果方法具有返回类型,我如何在该方法中设置NSAutoreleasePool?有办法做到这一点吗?像下面这样的方法:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation, AddressAnnotation>) annotation; 

或者在重写的方法中,如:

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated;

我可以在主.m文件中看到如下:

    int main(int argc, char *argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//Do anything here
        int retVal = UIApplicationMain(argc, argv, nil, nil);
        [pool release];
        return retVal;
    }

所以它应该是这样的?

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation, AddressAnnotation>) annotation
{
    NSAutoreleasePool *myPool = [[NSAutoreleasePool alloc] init];
    static NSString *reuseIdentifier = @"ident1";
    BOOL needsRelease = NO;
    // try to dequeue an existing pin view first
    MKPinAnnotationView *pinView = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseIdentifier];
    if (!pinView)
    {
        // if an existing pin view was not available, create one
        MKPinAnnotationView* pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
        needsRelease = YES;
    }
    //customize the annotation
    //...
    //release the autorelease pool
    [myPool drain];
    //autorelease now if allocated new view - if autoreleased on the same line as alloc/inited, it would be released with the pool
    if(needsRelease) [pinView autorelease];
    return pinView;
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation, AddressAnnotation>) annotation {

        here if u create annotation view with alloc or init or copy then u have to release them manually.
        remember every function inside which is not used with init or alloc or copy are autoreleased object.
        so dont worry about them.
        instead of pool u can create 
            //[annotationclass alloc] like this

        then u can use like this to return.so no memory leak here
        return [annonationView autorelease];
}

这是如何正确地使用返回值执行自动释放池。

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation, AddressAnnotation>) annotation {
id retVal;
NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
// do things here with the pool.
// save the return value to id retVal and it will be available later.
[pool release];
return retVal;
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation, AddressAnnotation>) annotation {
NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
[pool drain];
return annonationView;
}

明白了吗?

相关内容

  • 没有找到相关文章

最新更新