类返回NSMutabledata

时间:2011-06-04 15:28:48

标签: iphone xcode sdk nsmutabledata

我想写一个返回NSMutableData的类,我有这个代码,但无法管理它如何返回self。任何帮助都会很棒。

@interface ITumblr_QueryTumblr : NSMutableData {

    NSURLConnection* connection;
    NSMutableData* data;    

}



-(void)loadImageFromURL:(NSURL*)url {

    if (connection!=nil) { [connection release]; }
    if (data!=nil) { [data release]; }
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

}

-(void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {

    if (data==nil) {

        data = [[NSMutableData alloc] initWithCapacity:2048];

    }

    [data appendData:incrementalData];

}

-(void)connectionDidFinishLoading:(NSURLConnection*)theConnection {

    [connection release];
    connection=nil;

    [data release];
    data=nil;

}

2 个答案:

答案 0 :(得分:4)

虽然方法可以,但是类不会返回任何内容。要获得返回数据的方法,请使用

-(NSMutableData *)returnSomeData {
  return data;
}

或者,您只需从班级的实例中调用属性.data即可。

答案 1 :(得分:0)

假设您的网址上有一个包含字典的.plist文件,您必须将connectionDidFinishLoading修改为以下内容:

(void)connectionDidFinishLoading:(NSURLConnection*)theConnection {

    [connection release]; connection=nil;

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

     NSString *myFilePath = [documentsDirectoryPathstringByAppendingPathComponent:@"myfile.plist"];

     [data writeToFile:myFilePath atomicaly:YES];

    [data release]; data=nil;                           

     return [NSMutableDictionary dictionaryWithContentsOfFile:myFilePath];
}

但这是一个很难的方法,你应该使用:

 (id)dictionaryWithContentsOfURL:(NSURL *)aURL

因为它可以帮你免除麻烦