所以我首先編碼我所有的方法在視圖控制器與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];
}
我有點困惑,爲什麼你要創建一個視圖控制器。 – 2011-02-11 17:37:51
我從頭開始,讓這個工作 – zambono 2011-02-18 00:49:30