
你是否注意到:




上面的截图来自苹果官方文档。
那么方法(method)和函数(function)到底有什么区别?
我在S.O.上看到的答案:
Functions are code blocks that are unrelated to an object / class, just inherited from c, and you call them in the way:
// declaration
int fooFunction() {
return 0;
}
// call
int a;
a = fooFunction();
While methods are attached to class / instance (object) and you have to tell the class / object to perform them:
// declaration
- (int)fooMethod {
return 0;
}
// call
int a;
a = [someObjectOfThisClass fooMethod];
方法和函数的区别就是:
方法,与类和对象有关
函数,与类和对象无关
我们调用某个方法的时候,都是xx对象或xx类调用某个方法,但函数却是跟类或对象独立开的。
比如说延迟加载,用方法:
[self performSelector:@selector(doSomething) withObject:nil afterDelay:2];
用函数:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self doSomething];
});
更多讨论可参看:
https://stackoverflow.com/questions/155609/whats-the-difference-between-a-method-and-a-function#
网友评论