On a lot of NSURLConnection
examples I see the following lines:
NSURLConnection *theConnection = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
if(theConnection)
{
webData = [[NSMutableData data]retain];
}
else
...
I wonder - what is this supposed to do? and why does it work? I thought that data
is an accessor method, and since your not calling it on an instanciated object, it will return nil
, and by retaining it you actually do nothing.
This is the way I have seen to get data on connections like this:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:url] delegate:self s开发者_如何学JAVAtartImmediately:YES];
if( connection )
{
while (!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}
finished
is an ivar that gets set to YES
on connectionDidFinishLoading:
Can anyone clear this up for me? Which should be used and what's the difference?
[NSMutableData data]
is not an accessor but a so-called class method. You probably know [NSMutableData alloc]
, that too is a class method and means it is tied to the class but not an instance. The typical way to denote that a method is a class method is by prefixing it with a plus: +[NSMutableData data]
.
In this case, the method is inherited from the NSData
class (but does return an NSMutableData
instance, since you're calling it on that class).
An implementation might look like this:
@interface NSMutableData
+ (id)data
{
return [[[self alloc] init] autorelease];
}
@end
Note that self
in this case is the NSMutableData
class.
In other languages like C++, C# and Java (AFAIK) these would be methods that you specify with the static
keyword.
精彩评论