2011-02-05 55 views
0

所以我首先編碼我所有的方法在視圖控制器與NSOperationQueue。在做了一些研究和大量閱讀之後,我意識到我必須繼承我的loadImage操作,以便我可以使用isCancelled和cancelAllOperations。所以我繼續創建一個nsoperation類並從我的viewcontroller中調用它。 ALl方法被調用,即使是imageLoaded,但NSMutableDictionary仍然是空的。我使用字典填充我的tableviewcells使用URL作爲密鑰。另外請注意,視圖控制器中的操作調用是在視圖加載時由NSInvocationOperation調用的方法中。圖像沒有被添加到NSMutableDictionary,這是在一個NSOperation

@interface loadImages : NSOperation { 

    NSURL *targetURL; 
} 

@property(retain) NSURL *targetURL; 

- (id)initWithURL:(NSURL*)url; 

@end 

實現的NSOperation類的,包括一些其他的調用來調整圖像

@implementation loadImages 

@synthesize targetURL; 

- (id)initWithURL:(NSURL*)url 
{ 
    if (![super init]) return nil; 
    [self setTargetURL:url]; 
    return self; 
} 

- (void)dealloc { 
    [targetURL release], targetURL = nil; 
    [super dealloc]; 
} 

- (void)main { 

    NSLog(@"loadImages.m reached"); 

    StoriesTableViewController *stories = [[StoriesTableViewController alloc] init]; 

    NSMutableDictionary *tempDict = stories.filteredImagesDict; 

    UIImage *myImage = [[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[self targetURL]]]autorelease]; 

    UIImage *scaledImage = [[[UIImage alloc] init] autorelease]; 


    CGRect frame = CGRectMake(100.0f, 100.0f, 180.0f, 180.0f); 
    UIImageView *myImageFrame = [[UIImageView alloc] initWithFrame:frame]; 

    myImage = [[myImage croppedImage:[myImageFrame bounds]]retain]; 


    scaledImage = [[myImage resizedImage:CGSizeMake(120.0f, 120.0f) interpolationQuality:kCGInterpolationHigh]retain]; 

    [tempDict setValue:scaledImage forKey:[self targetURL]]; 


    [stories performSelectorOnMainThread:@selector(imageLoaded:) 
           withObject:myImage 
             waitUntilDone:YES]; 

    NSLog(@"targetURL %@",[self targetURL]); 
    NSLog(@"tempDict count: %d",tempDict.count); 

    [stories release]; 
    [myImage release]; 
    [myImageFrame release]; 
    [scaledImage release]; 
} 

創作的NSOperation對視圖 - 控制

for(int i=0;i<storyQuantity;i++) { 
     NSString *imageString = [[[storiesArray objectAtIndex:i] objectForKey: @"image"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; // must add trimming to remove characters 

     NSURL *url = [NSURL URLWithString:imageString]; 
     loadImages *imageOperation = [[loadImages alloc] initWithURL:url]; 
     [queue_ addOperation:imageOperation]; 
     [imageOperation release]; 

    } 
+0

我有點困惑,爲什麼你要創建一個視圖控制器。 – 2011-02-11 17:37:51

+0

我從頭開始,讓這個工作 – zambono 2011-02-18 00:49:30

回答

1

如果這樣運行沒有異常,字典仍然空的,這很可能意味着你的價值是零。

這是代碼中的一個常見問題,就像你在一個方法的結果中進入下一個方法。在任何時候,如果有問題,鏈條的其餘部分將無法工作。

爲了解決這個問題,我會從你將圖像分配到字典的位置開始。您可以使用斷點或NSLog來確定該點處圖像的值。我更喜歡使用NSLog,但是一個斷點可以讓你一次查看所有的值。如果scaledImage爲零,則檢查myImage。不斷追溯鏈條,直到找到價值從你期望的值到零的點爲止。

相關問題