访问块目标内的属性c

时间:2015-12-17 12:51:21

标签: objective-c properties block

- (IBAction)saveBtn:(id)sender {
    UIImage* imageToSave = [self imageByCombiningImage:self.backgroundImage.image withImage:self.tempImage.image];
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    // Request to save the image to camera roll

    [library writeImageToSavedPhotosAlbum:[imageToSave CGImage] orientation:(ALAssetOrientation)[imageToSave imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
        if (error) {
            NSLog(@"error");
        } else {
            CGFloat compression = 0.0;         
            NSData *imageData = UIImageJPEGRepresentation(imageToSave, compression);
            UIImage *compressedImage = [[UIImage alloc]initWithData:imageData];
            NSMutableString *imageName = [[NSMutableString alloc] initWithCapacity:0];

            CFUUIDRef theUUID = CFUUIDCreate(kCFAllocatorDefault);
            if (theUUID) {
                [imageName appendString:CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, theUUID))];
                CFRelease(theUUID);
            }
            [imageName appendString:@".png"];

            NSLog(@"Image name: %@", imageName);

            //Image Data to web service
            [self uploadImage:UIImageJPEGRepresentation(compressedImage, 1.0) filename:imageName];

            _savedImageURL = assetURL;
            [library assetForURL:_savedImageURL
                     resultBlock:resultblock
                    failureBlock:failureblock];
    }];
}

ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
    ALAssetRepresentation *rep = [myasset defaultRepresentation];
    CGImageRef iref = [rep fullResolutionImage];
    if (iref) {
        UIImage *largeimage = [UIImage imageWithCGImage:iref];
        //image Property needs to be access here
    }
};

我无法访问此块内的任何属性。就像我在.h文件中创建了一个UIImage属性,但我无法在该结果块中访问它。

2 个答案:

答案 0 :(得分:0)

如果您发布的代码实际上是您正在使用的代码,那么它将定义一个引用块的变量。但是该变量是类的一部分,因此您无法引用任何实例变量。

相反,变量位于任何类之外的“C顶级”。您可能希望将其转换为实例变量,例如:

@interface MyClass : SomeSuperClass
{
    // Define an instance variable.
    ALAssetsLibraryAssetForURLResultBlock resultblock;
}
@end

@implementation MyClass

- (void)someMethod
{
    // Initialize the variable in `init`, `viewDidLoad` or whichever
    // method suits you.
    resultblock = ^(ALAsset *myasset)
    {
        ALAssetRepresentation *rep = [myasset defaultRepresentation];
        CGImageRef iref = [rep fullResolutionImage];
        if (iref) {
            UIImage *largeimage = [UIImage imageWithCGImage:iref];
           //image Property needs to be access here
        }
   };
}

@end

您也可以使用属性。

答案 1 :(得分:-3)

下一个解决方案是你可以从整个控制器创建块属性,如下所示:

__block MyViewController *blocksafeSelf = self;

和内部块您可以使用此属性访问:

blocksafeSelf.myProperty;

或致电方法:

dispatch_async(dispatch_get_main_queue(), ^
      [blocksafeSelf processNewMessage:text]  
});