Objective c 无法在目标c中调用方法
我很难理解如何调用方法。代码如下:Objective c 无法在目标c中调用方法,objective-c,json,ios7,methods,xcode5,Objective C,Json,Ios7,Methods,Xcode5,我很难理解如何调用方法。代码如下: - (void)beachJSON { // Build the string to call Beach API NSString *urlString = [NSString stringWithFormat:@"http://nrw-bwq-dev-api.azurewebsites.net/api/Pull"]; // Create NSURL string from formatted string NSURL *url = [NSURL URLW
- (void)beachJSON
{
// Build the string to call Beach API
NSString *urlString = [NSString stringWithFormat:@"http://nrw-bwq-dev-api.azurewebsites.net/api/Pull"];
// Create NSURL string from formatted string
NSURL *url = [NSURL URLWithString:urlString];
// Setup and start async download
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Store incoming data into a string
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
results = [jsonString JSONValue];
}
- (NSArray *)getBeachList {
[self beachJSON];
return results;
}
我从另一个类调用getBeachList来填充“results”,beachJSON被称为fine,但我需要调用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
内
- (NSArray *)getBeachList
i、 就在这里
- (NSArray *)getBeachList {
[self beachJSON];
//This is where I want to call it to populate results before it is returned
return results;
}
调用getBeachList将调用beachJSON,但将跳过连接方法,而不保留'results'nil
如果我试着简单地
[self connection:(NSURLConnection *)connection didReceiveData:(NSData *)data]
我在那一行得到了预期的表达式错误
我对objective c非常陌生,所以任何帮助都会很好。你不应该自己打电话给
连接:didReceiveData:
。这是一个只应由NSURLConnection
实例触发的事件。据我所知,您唯一缺少的是start
调用,它实际上使NSURLConnection
执行请求
试试这个:
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
然后您应该看到您的NSURLConnection
实例将调用connection:didReceiveData:
的实现
如果要确保数据已完全加载,则应使用此事件:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
如果数据大小足够大,则会多次调用
连接:didReceiveData:
。每次NSURLConnection
接收数据时,它都会调用connection:didReceiveData:
connectiondFinishLoading:
仅在所有数据就绪时调用一次。您不需要调用此方法。
这是NSURLConnection的委托方法。您需要的是为connection设置一个委托,当它下载任何数据时,connection将调用该方法。
对不起,我应该指定从另一个类调用getBeachList。所以每次调用它时,beachJSON都会工作,但连接方法会被跳过。这会给我返回为零的结果。指定了什么?:)如果您不满意,请编辑您的问题。我对我的问题进行了进一步编辑,以澄清我试图做的事情。当我发布它的时候,应该确保它是100%清楚的。D:你能详细说明一下你为连接设置代理的意思吗?@Marushiru,对不起,你在连接初始化时就这样做了。如果您编写了[…initWithRequest:…委托:self],则连接对象将调用-connection:didReceiveData:。您不应该从getBeachList方法返回任何内容。您需要设置对连接实例的强引用。您必须[连接开始]。下载将开始,您将在didReceiveData中获得作为参数的数据片段:。您应该连接交付的每个数据对象的内容,以构建URL加载的完整数据。如果阅读“URL加载系统编程指南”,您将获得更多信息。