Iphone 自定义委托的问题

Iphone 自定义委托的问题,iphone,ios,delegates,asihttprequest,ios5,Iphone,Ios,Delegates,Asihttprequest,Ios5,这是我第一次尝试编写自己的代理。我正在使用iOS5 Beta 7并编写委托函数 它应该做的是一个表(MyTableController)加载一个电视频道列表。这是一个包含键“logotype”的字典,该键是指向图像标识的URL。 我创建了名为“Channel”的类和名为“ChannelDelegate”的委托。现在,当我的表执行cellforrowatinexpath时,它将启动我的通道类并调用函数getChannelImageForChannelId:externalreference:ind

这是我第一次尝试编写自己的代理。我正在使用iOS5 Beta 7并编写委托函数

它应该做的是一个表(
MyTableController
)加载一个电视频道列表。这是一个包含键“logotype”的字典,该键是指向图像标识的URL。 我创建了名为“
Channel
”的类和名为“
ChannelDelegate
”的委托。现在,当我的表执行
cellforrowatinexpath
时,它将启动我的通道类并调用函数
getChannelImageForChannelId:externalreference:indexPath
。到目前为止还不错,现在我的channel类检查文件是否存在于本地,如果不存在,它将下载它(使用
ASIHttpRequest
)。而且,到目前为止还不错。现在,当ASIHttpRequest在requestDidFinish上返回时,它会在几个结果之后消失。我注意到文件确实被下载了,因为经过几次尝试后,它就像一个符咒一样工作,因此我的委托似乎工作正常

这是我的代码:
CellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CurrentChannelInfoCell";

    CurrentChannelInfoCell *cell = (CurrentChannelInfoCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil){
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:nil options:nil];

        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[CurrentChannelInfoCell class]])
            {
                cell = (CurrentChannelInfoCell *)currentObject;
                break;
            }
        }
    }


    NSArray *keys = [self.content allKeys];
    id channelId = [keys objectAtIndex:indexPath.row];
    NSDictionary *channel = [self.content objectForKey:channelId];

    int cId = [(NSString*)channelId intValue];

    [cell.textLabel setText:[channel objectForKey:@"name"]];
    [cell.channelImage setHidden:YES];

    Channel *theChannel = [[Channel alloc] init];
    [theChannel setDelegate:self];
    [theChannel getChannelImageForChannelId:cId externalRefference:[channel objectForKey:@"logotype"] indexPath:indexPath];

    return cell;
}

- (void)didRecieveImageForChannel:(NSString*)imagePath indexPath:(NSIndexPath*)indexPath
{
    NSLog(@"Did recieve the it.!");
}
我的委托,
ChannelDelegate.h

#import <Foundation/Foundation.h>

@class Channel;

@protocol ChannelDelegate <NSObject>

@optional
- (void)didRecieveImageForChannel:(NSString*)imagePath indexPath:(NSIndexPath*)indexPath;

@end
#import <Foundation/Foundation.h>
#import "ChannelDelegate.h"

#import "Reachability.h"
#import "ASIHTTPRequest.h"
#import "ASINetworkQueue.h"
#import "ASIFormDataRequest.h"

@interface Channel : NSOperation <NSObject, ASIHTTPRequestDelegate>
{   
    ASINetworkQueue *networkQueue;

    // Called on the delegate (if implemented) when the request completes successfully.
    id <ChannelDelegate> delegate;

    SEL didRecieveImageForChannelSelector;
}

@property (strong, nonatomic) id delegate;
@property (assign) SEL didRecieveImageForChannelSelector;

- (void)getChannelImageForChannelId:(int)channelId externalRefference:(NSString*)url indexPath:(NSIndexPath*)indexPath;
- (id)delegate;

@end
Channel.m

#import "Channel.h"
#import <objc/runtime.h>

@implementation Channel

static char kAssociationKey;

@synthesize didRecieveImageForChannelSelector;
@synthesize delegate;

- (void)getChannelImageForChannelId:(int)channelId externalRefference:(NSString*)url indexPath:(NSIndexPath*)indexPath
{
    [self setDidRecieveImageForChannelSelector:@selector(didRecieveImageForChannel:indexPath:)];

    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

    NSString *imagePath = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.gif", channelId]];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];

    if (fileExists)
    {
        NSLog(@"Downloaded image!");
        [[self delegate] performSelector:[self didRecieveImageForChannelSelector] withObject:imagePath withObject:indexPath];
    }
    else {
        NSLog(@"Need to fetch it.!");

        NSURL *theUrl = [NSURL URLWithString:url];

        ASINetworkQueue *newQueue = [[ASINetworkQueue alloc] init];
        [newQueue setRequestDidFinishSelector:@selector(channelImageFetched:)];
        [newQueue setRequestDidFailSelector:@selector(processFailed:)];
        [newQueue setDelegate:self];

        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:theUrl];
        [request setTimeOutSeconds:60];
        [request setDownloadDestinationPath:imagePath];
        [newQueue addOperation:request];

        objc_setAssociatedObject(request, &kAssociationKey, indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

        [newQueue go];
    }
}

- (id)delegate
{
    id d = delegate;
    return d;
}

- (void)setDelegate:(id)newDelegate
{
    delegate = newDelegate;
}

// Handle process two
- (void)channelImageFetched:(ASIHTTPRequest *)request 
{
    NSLog(@"channelImageFetched!");


    NSIndexPath *indexPath = objc_getAssociatedObject(request, &kAssociationKey);
    NSString *imagePath = request.downloadDestinationPath;

    [[self delegate] performSelector:[self didRecieveImageForChannelSelector] withObject:imagePath withObject:indexPath];    

    NSLog(@"File downloaded!");
}

- (void) processFailed:(ASIHTTPRequest *)request
{   
    NSError *error = [request error];

    UIAlertView *errorView;

    errorView = [[UIAlertView alloc]
                 initWithTitle: NSLocalizedString(@"Whoops!", @"Errors")
                 //              message: NSLocalizedString(@"An error occured while preforming the request. Please try again.", @"Network error")
                 message: [error localizedDescription]
                 delegate: self
                 cancelButtonTitle: NSLocalizedString(@"Close", @"Errors") otherButtonTitles: nil];

    [errorView show];

    /*  NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
     [request error], @"Error",
     [request url], @"URL",
     [[NSDate alloc] init], @"timestamp", nil];

     [FlurryAPI logEvent:@"APNS-Could not fetch data." withParameters:dictionary timed:YES];
     */
}

@end
#导入“Channel.h”
#进口
@实施渠道
静态字符关联键;
@为通道选择器合成DID接收图像;
@综合代表;
-(void)getChannelImageForChannelId:(int)channelId外部引用:(NSString*)url索引XPath:(NSIndexPath*)索引XPath
{
[self-SetDidReceiveImageForChannel选择器:@selector(DidReceiveImageForChannel:indexPath:)];
NSString*documentsPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)对象索引:0];
NSString*imagePath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@“%d.gif”,channelId]];
BOOL fileExists=[[NSFileManager defaultManager]fileExistsAtPath:imagePath];
如果(文件存在)
{
NSLog(@“下载的图像!”);
[[self-delegate]性能选择器:[self-DiReceiveImageForChannelSelector]带对象:imagePath带对象:indexPath];
}
否则{
NSLog(@“需要获取它!”;
NSURL*theUrl=[NSURL-URLWithString:url];
ASINetworkQueue*newQueue=[[ASINetworkQueue alloc]init];
[newQueue setRequestDidFinishSelector:@selector(channelImageFetched:)];
[newQueue setRequestDidFailSelector:@selector(processFailed:)];
[newQueue setDelegate:self];
ASIHTTPRequest*request=[AsiHttpRequestWithURL:theUrl];
[请求setTimeOutSeconds:60];
[请求setDownloadDestinationPath:imagePath];
[newQueue addOperation:request];
objc_setAssociatedObject(请求、kAssociationKey、indexPath、objc_关联、保留、非原子);
[newQueue go];
}
}
-(id)代表
{
id d=代表;
返回d;
}
-(void)setDelegate:(id)newDelegate
{
delegate=newDelegate;
}
//处理流程二
-(void)channelImageFetched:(ASIHTTPRequest*)请求
{
NSLog(@“channelImageFetched!”);
NSIndexPath*indexPath=objc_getAssociatedObject(请求和kAssociationKey);
NSString*imagePath=request.downloadDestinationPath;
[[self-delegate]性能选择器:[self-DiReceiveImageForChannelSelector]带对象:imagePath带对象:indexPath];
NSLog(@“文件已下载!”);
}
-(void)processFailed:(ASIHTTPRequest*)请求失败
{   
n错误*错误=[请求错误];
UIAlertView*错误视图;
errorView=[[UIAlertView alloc]
initWithTitle:NSLocalizedString(@“哎哟!”,@“错误”)
//消息:NSLocalizedString(@“执行请求时出错。请重试。”,@“网络错误”)
消息:[错误本地化描述]
代表:赛尔夫
取消按钮提示:NSLocalizedString(@“Close”,@“Errors”)其他按钮提示:nil];
[错误视图显示];
/*NSDictionary*dictionary=[NSDictionary dictionary WithObjectsAndKeys:
[请求错误],@“错误”,
[请求url],@“url”,
[[NSDate alloc]init],@“timestamp”,nil];
[FlurryAPI logEvent:@“APNS无法获取数据。”参数:dictionary timed:YES];
*/
}
@结束
我收到的错误似乎不时不同,但这些似乎是我得到的错误:

2011-09-26 13:11:57.605电视体育【4541:ef03】完成
2011-09-26 13:11:57.609电视体育[4541:ef03]下载图片
2011-09-26 13:11:57.610电视体育[4541:ef03]确实收到了它
2011-09-26 13:11:57.613电视体育[4541:ef03]需要取回 如果
2011-09-26 13:11:57.616电视体育[4541:ef03]需要 把钥匙拿来
2011-09-26 13:11:57.618电视体育[4541:ef03] 我需要把它拿回来
2011-09-26 13:11:57.621 TVSOPERTS[4541:ef03]需要把它拿回来
2011-09-26 13:11:57.624电视体育[4541:ef03]需要取回它
2011-09-26 13:11:57.629电视体育[4541:ef03]需要取回 它
2011-09-26 13:11:57.633电视体育[4541:ef03]需要 把钥匙拿来
2011-09-26 13:11:57.663电视体育[4541:ef03] 我需要把它拿回来
2011-09-26 13:11:57.669 TVSOPERTS[4541:ef03]需要把它拿回来
2011-09-26 13:11:57.846电视体育[4541:ef03]-[UIDeviceWhiteColor channelImageFetched::发送到实例的选择器无法识别 0x65a1e30
2011-09-26 13:11:57.847电视体育[4541:ef03]* 由于未捕获异常而终止应用程序 “NSInvalidArgumentException”,原因:“-[UIDeviceWhiteColor channelImageFetched::发送到实例的选择器无法识别 0x65a1e30'
*
第一次抛出调用堆栈:
(0x15da272 0x1769ce6 0x15dbf0d 0x1540e2f 0x1540c12 0x15dc092 0x3adf8 0x15dc092 0x24c43 0x15dc092 0xef9fac 0x15aec0f 0x15118c3 0x15111a4 0x1510b04 0x1510a1b 0x1ce6f67 0x1ce702c 0x608cf2 0x2718 0x2675 0x1)
终止调用的抛出 异常(gdb)

或者我在ASIHTTPRequest中的一行上获得了EXC_BAD_访问权限(我无法复制最后10次尝试)

谁能看出我做错了什么?Whe
[...]
    if (fileExists)
    {
        NSLog(@"Downloaded image!");
        [[self delegate] performSelector:[self didRecieveImageForChannelSelector] withObject:imagePath withObject:indexPath];
    }
    else {
        NSLog(@"Need to fetch the image!");

        NSURL *theUrl = [NSURL URLWithString:url];

        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:theUrl];
        [request setDidFinishSelector:@selector(channelImageFetched:)];
        [request setDidFailSelector:@selector(processFailed:)];
        [request setTimeOutSeconds:60];
        [request setDownloadDestinationPath:imagePath];

        objc_setAssociatedObject(request, &kAssociationKey, indexPath, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

        [request startAsynchronous];
    }
[...]