标题中我使用了 Objective C,但这个问题对于其他 OOP 语言也是可行的,我的问题是:下面哪个声明(示例)更有效?
1)
NSString *urlString=@"string_literal_for_URL";
NSURL *url = [NSURL urlWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:40];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:requestFromLogin
delegate:self];
2)
NSURLRequest *requestFromLogin = [NSURLRequest requestWithURL:[NSURL URLWithString[NSString stringWithFormat:@"http://%@:%@/ipad/login.php?username=%@&password=%@",server.text,port.text,username.text,password.text]]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:40];
[[NSURLConnection alloc] initWithRequest:requestFromLogin delegate:self];
注意:据我记得CS193p Video Lectures iOS 擅长惰性实例化(据我所知,第一个示例更好)但我不确定..任何人都可以从 OOP 的角度给出答案..提前致谢
最佳答案
当使用 ARC 编译代码并关闭优化时,存在细微差别:第一个示例会额外增加和减少对 url
对象的引用计数。然而,当优化打开时,编译器应该能够找出 url
变量除了调用 NSURLRequest
的初始化器之外没有被使用,并优化它.
关于objective-c - 声明 Objective C 对象时哪个更有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11581396/